From f0a86a6479480566df0c9bb3d1299e961963cd95 Mon Sep 17 00:00:00 2001 From: David Vereb Date: Thu, 5 Dec 2024 15:34:20 -0500 Subject: [PATCH] Day 5 Part 2. --- 2024/5/main.cpp | 79 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 54 insertions(+), 25 deletions(-) diff --git a/2024/5/main.cpp b/2024/5/main.cpp index c1accf9..687a849 100644 --- a/2024/5/main.cpp +++ b/2024/5/main.cpp @@ -7,6 +7,8 @@ #include #include +bool IsBad(const std::vector &row, const std::map> &rules, size_t &bad_i); + int main() { const std::string filename = "data.txt"; @@ -94,34 +96,34 @@ int main() // For each production run: for(auto row : production) { - std::set already_passed; - bool bad = false; - // For each page number in that production run: - for(auto num : row) - { - // Check against all page numbers it shouldn't print after - for(auto before : rules[num]) - { - // If found, it's a bad row! - if(std::find(already_passed.begin(), already_passed.end(), before) != already_passed.end()) - { - bad = true; - break; - } - } - - // Keep track of numbers we've looked at already: - already_passed.insert(num); - } + size_t bad_idx; + auto bad = IsBad(row, rules, bad_idx); + // Part 1: if(!bad) total += row[row.size() / 2]; - // else - // std::cout << "not "; - // std::cout << "safe: "; - // for(auto num : row) - // std::cout << num << ","; - // std::cout << std::endl; + // Part 2: + else + { + std::vector working; + for(auto n : row) + working.push_back(n); + + while(IsBad(working, rules, bad_idx)) + { + auto temp = working[bad_idx]; + working.erase(working.begin() + bad_idx); + working.insert(working.begin(), temp); + + // Debug Sort: + // std::cout << "Trying again: "; + // for(auto i : working) + // std::cout << i << ","; + // std::cout << std::endl; + } + + total_pt2 += working[working.size() / 2]; + } } std::cout << " Total: " << total << std::endl; @@ -129,3 +131,30 @@ int main() return 0; } + +bool IsBad(const std::vector &row, const std::map> &rules, size_t &bad_i) +{ + std::set already_passed; + bool bad = false; + // For each page number in that production run: + int i = 0; + for(auto num : row) + { + // Check against all page numbers it shouldn't print after + for(auto before : rules.at(num)) + { + // If found, it's a bad row! + if(std::find(already_passed.begin(), already_passed.end(), before) != already_passed.end()) + { + bad = true; + bad_i = i; + break; + } + } + + // Keep track of numbers we've looked at already: + already_passed.insert(num); + ++i; + } + return bad; +}