Day 7 puzzle

master
Wynd 2022-12-07 15:08:32 +02:00
parent 70446c8402
commit 405a001817
6 changed files with 1104 additions and 7 deletions

5
Cargo.lock generated
View File

@ -12,6 +12,7 @@ dependencies = [
"day4", "day4",
"day5", "day5",
"day6", "day6",
"day7",
] ]
[[package]] [[package]]
@ -37,3 +38,7 @@ version = "0.1.0"
[[package]] [[package]]
name = "day6" name = "day6"
version = "0.1.0" version = "0.1.0"
[[package]]
name = "day7"
version = "0.1.0"

View File

@ -17,3 +17,4 @@ day3 = { path = "./day3" }
day4 = { path = "./day4" } day4 = { path = "./day4" }
day5 = { path = "./day5" } day5 = { path = "./day5" }
day6 = { path = "./day6" } day6 = { path = "./day6" }
day7 = { path = "./day7" }

8
day7/Cargo.toml 100644
View File

@ -0,0 +1,8 @@
[package]
name = "day7"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

1010
day7/src/input.txt 100644

File diff suppressed because it is too large Load Diff

78
day7/src/lib.rs 100644
View File

@ -0,0 +1,78 @@
use std::collections::HashMap;
const ROOT: &str = "/";
const TOTAL_SPACE: u64 = 70_000_000;
const UPDATE_SPACE: u64 = 30_000_000;
pub fn start() {
let input = include_str!("input.txt").replace("\r", "");
let input = input.lines().collect::<Vec<&str>>();
let dirs = get_dirs(input);
let sum1: u64 = dirs
.iter()
.filter_map(|(_, &size)| {
if size <= 100_000 {
Some(size)
}
else {
None
}
})
.sum();
println!("Part 1: {}", sum1);
let used_space: u64 = dirs[ROOT];
let free_space = TOTAL_SPACE - used_space;
let needed_space = UPDATE_SPACE - free_space;
let mut dirs = dirs
.iter()
.filter_map(|(_, &size)| {
if size >= needed_space {
Some(size)
}
else {
None
}
})
.collect::<Vec<_>>();
dirs.sort();
println!("Part 2: {}", dirs[0])
}
fn get_dirs(lines: Vec<&str>) -> HashMap<String, u64> {
let mut cwd: Vec<String> = vec![];
let mut dirs: HashMap<String, u64> = HashMap::new();
for cmd in lines {
if cmd.starts_with("$ cd") {
match &cmd[5..] {
"/" => {
cwd = vec![ROOT.to_string()];
}
".." => {
cwd.pop();
}
x => {
cwd.push(x.to_string());
}
}
}
else if cmd.starts_with("$ ls") || cmd.starts_with("dir") {
continue;
}
else {
let (size, _) = cmd.split_once(" ").unwrap();
let size = size.parse::<u64>().unwrap();
for i in 0..cwd.len() {
let key = cwd[0..=i].join("/").to_string();
dirs.entry(key).and_modify(|a| *a += size).or_insert(size);
}
}
}
dirs
}

View File

@ -1,9 +1,4 @@
fn main() { fn main() {
// day1::start(); day7::start();
// day2::start();
// day3::start();
// day4::start();
// day5::start();
day6::start();
} }