This commit is contained in:
TriMill 2022-12-07 01:25:00 -05:00
parent 1cce3469bb
commit 6c33771a96
2 changed files with 99 additions and 0 deletions

48
examples/day07_1.rs Normal file
View File

@ -0,0 +1,48 @@
use std::{collections::{HashMap, HashSet}};
fn main() {
let mut lines = std::io::stdin().lines().map(|x| x.unwrap()).peekable();
let mut files: HashMap<String, usize> = HashMap::new();
let mut dirs: HashSet<String> = HashSet::new();
let mut cd: Vec<String> = Vec::new();
while let Some(line) = lines.next() {
let parts = line.split(" ").collect::<Vec<&str>>();
match parts[1] {
"cd" => {
match parts[2] {
".." => { cd.pop(); },
"/" => cd = Vec::new(),
x => cd.push(x.to_owned()),
}
dirs.insert(cd.join("/"));
}
"ls" => while let Some(line) = lines.peek() {
if line.starts_with("$") {
break
}
let line = lines.next().unwrap();
let parts: Vec<&str> = line.split(" ").collect();
if parts[0] != "dir" {
let size: usize = parts[0].parse().unwrap();
let name = parts[1].to_owned();
let mut f = cd.clone();
f.push(name);
files.insert(f.join("/"), size);
}
}
_ => todo!()
}
}
let mut sizes: HashMap<String, usize> = HashMap::new();
for dir in dirs {
let mut size = 0;
for file in &files {
if file.0.starts_with(&dir) {
size += file.1;
}
}
sizes.insert(dir, size);
}
let total: usize = sizes.iter().filter(|(_, v)| **v <= 100000).map(|(_, v)| v).sum();
println!("{}", total);
}

51
examples/day07_2.rs Normal file
View File

@ -0,0 +1,51 @@
use std::{collections::{HashMap, HashSet}};
fn main() {
let mut lines = std::io::stdin().lines().map(|x| x.unwrap()).peekable();
let mut files: HashMap<String, usize> = HashMap::new();
let mut dirs: HashSet<String> = HashSet::new();
let mut cd: Vec<String> = Vec::new();
while let Some(line) = lines.next() {
let parts = line.split(" ").collect::<Vec<&str>>();
match parts[1] {
"cd" => {
match parts[2] {
".." => { cd.pop(); },
"/" => cd = Vec::new(),
x => cd.push(x.to_owned()),
}
dirs.insert(cd.join("/"));
}
"ls" => while let Some(line) = lines.peek() {
if line.starts_with("$") {
break
}
let line = lines.next().unwrap();
let parts: Vec<&str> = line.split(" ").collect();
if parts[0] != "dir" {
let size: usize = parts[0].parse().unwrap();
let name = parts[1].to_owned();
let mut f = cd.clone();
f.push(name);
files.insert(f.join("/"), size);
}
}
_ => todo!()
}
}
let mut sizes: HashMap<String, usize> = HashMap::new();
for dir in dirs {
let mut size = 0;
for file in &files {
if file.0.starts_with(&dir) {
size += file.1;
}
}
sizes.insert(dir, size);
}
let root_size = sizes[""];
let free_space = 70000000 - root_size;
let to_free = 30000000 - free_space;
let smallest = sizes.values().filter(|x| **x >= to_free).min().unwrap();
println!("{}", smallest);
}