Day 5 Part 2.

This commit is contained in:
David Vereb 2024-12-05 15:34:20 -05:00
parent 80555c4d9c
commit f0a86a6479

View File

@ -7,6 +7,8 @@
#include <string> #include <string>
#include <vector> #include <vector>
bool IsBad(const std::vector<long> &row, const std::map<long, std::set<long>> &rules, size_t &bad_i);
int main() int main()
{ {
const std::string filename = "data.txt"; const std::string filename = "data.txt";
@ -94,34 +96,34 @@ int main()
// For each production run: // For each production run:
for(auto row : production) for(auto row : production)
{ {
std::set<long> already_passed; size_t bad_idx;
bool bad = false; auto bad = IsBad(row, rules, bad_idx);
// 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);
}
// Part 1:
if(!bad) if(!bad)
total += row[row.size() / 2]; total += row[row.size() / 2];
// else // Part 2:
// std::cout << "not "; else
// std::cout << "safe: "; {
// for(auto num : row) std::vector<long> working;
// std::cout << num << ","; for(auto n : row)
// std::cout << std::endl; 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; std::cout << " Total: " << total << std::endl;
@ -129,3 +131,30 @@ int main()
return 0; return 0;
} }
bool IsBad(const std::vector<long> &row, const std::map<long, std::set<long>> &rules, size_t &bad_i)
{
std::set<long> 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;
}