From 7ef32aafcb4fc1ccd493dff865ecd46ae8023c63 Mon Sep 17 00:00:00 2001 From: David Vereb Date: Thu, 8 Dec 2022 23:02:53 -0500 Subject: [PATCH] #7 part 2 on my first try, too. Daaaang. --- 2022/7/main.cpp | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/2022/7/main.cpp b/2022/7/main.cpp index 1b5327c..c24a047 100644 --- a/2022/7/main.cpp +++ b/2022/7/main.cpp @@ -150,6 +150,25 @@ unsigned long PartOne(File *file, unsigned long &grand_total) return rtn; } +void PartTwo(File *file, unsigned long at_least, File *&smallest) +{ + Folder *folder = dynamic_cast(file); + if(folder) + { + if(folder->Size() >= at_least && folder->Size() < smallest->Size()) + { + std::cout << "New smallest size of " << folder->Size() << " by folder \"" + << folder->Filename() << "\"." << std::endl; + smallest = file; + } + + for(File *file : folder->Files()) + PartTwo(file, at_least, smallest); + } + + return; +} + int main() { std::ifstream ifs("data.txt"); @@ -226,7 +245,20 @@ int main() unsigned long grand_total = 0; PartOne(&root, grand_total); - std::cout << "Grand Total: " << grand_total << std::endl; + std::cout << "Grand Total (part 1): " << grand_total << std::endl; + + const unsigned long max_space = 70000000; + const unsigned long space_needed = 30000000; + const unsigned long currently_used = root.Size(); + const unsigned long currently_unused = max_space - currently_used; + const unsigned long amt_to_remove = space_needed - currently_unused; + + File *file_to_remove = &root; + PartTwo(&root, amt_to_remove, file_to_remove); + + std::cout << "Remove \"" << file_to_remove->Filename() << "\" to free up " + << file_to_remove->Size() << " which is the smallest amount >= " + << amt_to_remove << " (part 2)." << std::endl; return 0; }