1
0
This commit is contained in:
Jack Bond-Preston 2022-12-23 23:01:37 +00:00
parent 52a17ff632
commit 64820c0251
Signed by: jack
GPG Key ID: 010071F1482BA852
5 changed files with 1129 additions and 0 deletions

View File

@ -7,4 +7,5 @@ members = [
"day4", "day4",
"day5", "day5",
"day6", "day6",
"day7",
] ]

9
day7/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[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]
petgraph = "0.6.2"

1020
day7/input.txt Normal file

File diff suppressed because it is too large Load Diff

23
day7/sample_input.txt Normal file
View File

@ -0,0 +1,23 @@
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 ks

76
day7/src/main.rs Normal file
View File

@ -0,0 +1,76 @@
use std::borrow::BorrowMut;
use petgraph::*;
use petgraph::dot::*;
use petgraph::prelude::*;
fn do_weights(g: &mut Graph<(String, u64), ()>, root_dir: NodeIndex<u32>) {
for edge in g.clone().edges_directed(root_dir, Outgoing) {
let mut target_weight = g.node_weight(edge.target()).unwrap();
if target_weight.1 == 0 {
do_weights(g, edge.target());
target_weight = g.node_weight(edge.target()).unwrap();
}
g.node_weight_mut(root_dir).unwrap().1 += target_weight.1;
}
}
fn main() {
const INPUT: &str = include_str!("../input.txt");
let mut g = DiGraph::<(String, u64), (), u32>::new();
let invalid_index: NodeIndex<u32> = NodeIndex::from(u32::MAX);
let mut curr_dir: NodeIndex<u32> = invalid_index;
let mut root_dir: NodeIndex<u32> = invalid_index;
for line in INPUT.lines() {
if line.starts_with("$ cd") {
let new_dir = &line[5..];
if new_dir == ".." {
curr_dir = g.edges_directed(curr_dir, Incoming).next().unwrap().source();
} else {
let prev_dir = curr_dir;
curr_dir = g.add_node((new_dir.to_string() + "/", 0));
if prev_dir == invalid_index {
root_dir = curr_dir;
} else {
g.add_edge(prev_dir, curr_dir, ());
}
}
}
else if line.starts_with("$ ls") {
continue;
}
else {
let (size, name) = line.split_once(' ').unwrap();
if size == "dir" {
continue;
}
let size: u64 = size.parse().unwrap();
let n = g.add_node((name.to_string(), size));
g.add_edge(curr_dir, n, ());
}
}
do_weights(g.borrow_mut(), root_dir);
println!("{:?}\n\n", Dot::with_config(&g, &[Config::EdgeNoLabel]));
let total = g.node_weights().filter(|(n, w)| { n.ends_with("/") && *w <= 100000 }).map(|(_, w)| { w }).sum::<u64>();
println!("total: {total}");
let used_space = g.node_weight(root_dir).unwrap().1;
let free_space = 70000000 - used_space;
let need_to_free = 30000000 - free_space;
let mut delete = g.node_weights().filter(|(n, w)| { n.ends_with("/") && *w > need_to_free }).map(|(_, w)| { w }).collect::<Vec<&u64>>();
delete.sort();
let delete = delete[0];
println!("delete size: {delete}");
}