Day 5 Part 2.
This commit is contained in:
parent
80555c4d9c
commit
f0a86a6479
@ -7,6 +7,8 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
bool IsBad(const std::vector<long> &row, const std::map<long, std::set<long>> &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<long> 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<long> 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<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;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user