Add solution for "Day 5: Print Queue", part 2

This commit is contained in:
Stefan Müller 2024-12-05 20:24:53 +01:00
parent 861a51bad7
commit bc3edfd93c
2 changed files with 18 additions and 5 deletions

View File

@ -13,6 +13,7 @@
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <http://www.gnu.org/licenses/>.
#include <algorithm>
#include <sstream>
#include <vector>
@ -77,7 +78,8 @@ void PrintQueue::processUpdatePages(const std::string& line)
std::stringstream stream{ line };
std::string token;
auto isCorrectOrder{ true };
while (isCorrectOrder && std::getline(stream, token, ','))
// We completely construct 'pages' for part 2, even if the ordering is not correct.
while (std::getline(stream, token, ','))
{
size_t page = std::stoi(token);
size_t i{ 0 };
@ -86,14 +88,19 @@ void PrintQueue::processUpdatePages(const std::string& line)
isCorrectOrder = !orderingRules_[page][pages[i]];
i++;
}
if (isCorrectOrder)
{
pages.push_back(page);
}
pages.push_back(page);
}
if (isCorrectOrder)
{
part1 += pages[pages.size() / 2];
}
else
{
// This works because the input defines a complete ordering on the occurring
// page numbers.
std::sort(pages.begin(), pages.end(),
[&](int const& a, int const& b) { return orderingRules_[a][b]; });
part2 += pages[pages.size() / 2];
}
}

View File

@ -38,6 +38,12 @@ A simple [finite state machine](AdventOfCode2024/StringStateMachine.h) crawling
For this puzzle I added a class for [points in two-dimensional space](AdventOfCode2024/Point2.h), so I can use these for simplifying directional computations. With that, the algorithm looks for all `X` and `A` for part 1 and 2, respectively, and tries to find the remaining characters, starting from that `X` or `A`.
### Day 5: Print Queue
:mag_right: Puzzle: <https://adventofcode.com/2024/day/5>, :white_check_mark: Solver: [`PrintQueue.cpp`](AdventOfCode2024/PrintQueue.cpp)
My implementation uses an ordering matrix (a two-dimensional boolean array) to track which page combinations are ordered, and then queries that matrix for each ordered combination of pages in a single line. The same matrix can then also be used for a custom sort function for part 2.
## License
Copyright (C) 2024 Stefan Müller