Day 7 I don't know what I did

This commit is contained in:
Max Känner 2022-12-14 15:25:46 +01:00
parent cd2d6f4452
commit 163029eaeb

View File

@ -1,5 +1,6 @@
use std::{fs::read_to_string, iter::Peekable, str::Lines}; use std::{collections::HashMap, fs::read_to_string, iter::Peekable, str::Lines};
/*
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug)]
struct File { struct File {
name: String, name: String,
@ -115,3 +116,68 @@ fn main() {
let sol2 = sizes.filter(|s| s >= &additional).min().unwrap(); let sol2 = sizes.filter(|s| s >= &additional).min().unwrap();
println!("Deleting Directory with size {sol2}"); println!("Deleting Directory with size {sol2}");
} }
*/
fn main() {
let input = read_to_string("input.txt").unwrap();
let mut cwd = "/".to_owned();
let mut files = HashMap::new();
for line in input.lines() {
let line = line.split_whitespace().collect::<Vec<_>>();
match line.len() {
3 => match line[2] {
"/" => cwd = "/".to_owned(),
".." => {
cwd = {
if cwd == "/" {
cwd
} else {
let dirs = cwd.split_inclusive('/').collect::<Vec<_>>();
let nwd = dirs[..(dirs.len() - 1)]
.iter()
.fold(String::new(), |s, v| s + v);
nwd
}
}
}
dir => cwd = cwd + dir + "/",
},
2 => {
if (line[0] != "$") && (line[0] != "dir") {
let size = line[0].parse::<usize>().unwrap();
let path = cwd.clone() + line[1];
files.insert(path, size);
}
}
_ => (),
}
}
let mut directories = HashMap::new();
for (path, size) in files {
let mut folders = path
.split_terminator('/')
.map(|s| s.to_owned())
.collect::<Vec<String>>();
folders.pop();
for (index, folder) in folders.clone().iter().enumerate() {
let previus = if index > 0 { &folders[index - 1] } else { "" };
folders[index] = previus.to_owned() + folder + "/";
}
for folder in folders {
*directories.entry(folder).or_insert(0) += size;
}
}
let result1: usize = directories.values().filter(|&&size| size < 100_000).sum();
const TOTAL_SPACE: usize = 70000000;
const NEEDED_FREE: usize = 30000000;
let used = *directories.entry("/".to_owned()).or_insert(0);
let free = TOTAL_SPACE - used;
let additional = NEEDED_FREE - free;
let result2: usize = directories
.values()
.filter(|&&size| size >= additional)
.min()
.map(|size| *size)
.unwrap_or(0);
println!("{result1} bytes used by directories smaller than 100000. {result2} Bytes removed by the smallest directory");
}