diff --git a/AdventOfCode2024/PrintQueue.cpp b/AdventOfCode2024/PrintQueue.cpp
index 65bdf9d..dee3eba 100644
--- a/AdventOfCode2024/PrintQueue.cpp
+++ b/AdventOfCode2024/PrintQueue.cpp
@@ -13,6 +13,7 @@
// You should have received a copy of the GNU General Public License along with
// this program. If not, see .
+#include
#include
#include
@@ -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];
+ }
}
diff --git a/README.md b/README.md
index c6fe225..a67202d 100644
--- a/README.md
+++ b/README.md
@@ -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: , :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