1
0

Solved day 7 part 2

This commit is contained in:
Pcornat 2023-09-20 20:53:10 +02:00
parent 9a5252b635
commit 0ee7c433e3
Signed by: Pcornat
GPG Key ID: 2F3932FF46D9ECA0
3 changed files with 1049 additions and 2 deletions

1027
prob7_part2.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -60,5 +60,9 @@ fn main() -> Result<()> {
let solution = prob7::solve_part1(include_str!("../prob7_part1.txt"))?;
println!("Solution for problem 7 part 1: {solution}");
}
{
let solution = prob7::solve_part2(include_str!("../prob7_part2.txt"))?;
println!("Solution for problem 7 part 2: {solution}");
}
Ok(())
}

View File

@ -113,7 +113,6 @@ fn generate_tree(content: &str) -> color_eyre::Result<Tree<FsEntry>> {
let mut curr = root;
for line in lines {
println!("{line:?}");
match line {
Line::Command(cmd) => match cmd {
Command::Ls => {}
@ -136,7 +135,7 @@ fn generate_tree(content: &str) -> color_eyre::Result<Tree<FsEntry>> {
Line::Entry(entry) => match entry {
Entry::Dir(_) => {}
Entry::File(size, name) => {
curr = tree.insert(
tree.insert(
Node::new(FsEntry { path: name, size }),
InsertBehavior::UnderNode(&curr),
)?;
@ -157,3 +156,20 @@ pub fn solve_part1(content: &str) -> color_eyre::Result<u64> {
.sum::<u64>();
Ok(sum)
}
pub fn solve_part2(content: &str) -> color_eyre::Result<u64> {
let total_space = 70000000_u64;
let tree = generate_tree(content)?;
let used_space = total_size(&tree, tree.get(tree.root_node_id().unwrap())?)?;
let free_space = total_space.checked_sub(dbg!(used_space)).unwrap();
let needed_free_space = 30000000_u64;
let minimum_space_to_free = needed_free_space.checked_sub(free_space).unwrap();
let size_to_remove = tree
.traverse_pre_order(tree.root_node_id().unwrap())?
.filter(|n| !n.children().is_empty())
.map(|n| total_size(&tree, n).unwrap())
.filter(|&s| s >= minimum_space_to_free)
.min().unwrap();
Ok(size_to_remove)
}