Daily bit(e) of C++ | Advent of Code: Day 7
Daily bit(e) of C++ #340, Advent of Code using Modern C++: Day 7.
Welcome to day 7 of Advent of Code using Modern C++. Before you start reading, I highly encourage you to try to solve the two problems yourself: https://adventofcode.com/2023/day/7.
If you missed it, I have prepared a template repository for C++, with a development environment (through a devcontainer) with a bleeding edge version of the C++ toolchain: https://github.com/HappyCerberus/aoc-2023-cpp.
Today, we are analyzing “Poker” hands.
Part one
Ultimately, we aim to represent each hand and support ordering for the representation. That way, we can sort all hands and produce the desired sum.
This leaves today’s problem mostly a mechanical exercise, with the translation from hand to its strength being the outlier. I picked a verbose approach, spelling out everything in code; you could compress much of the explicit code into arrays, maps and matrices.
Let’s start with the representation of a Card. A Card also needs to support ordering. We will need that to compare hands that are of equal value.
With this, we can represent a hand. The big piece of functionality is taking five cards and translating that into the hand value.
Instead of sorting the frequencies and analyzing the first two elements, you could also work off the sum.
With the representation finished, we can put this together. We extract each hand from the input, sort the hands by value, and then produce the total sum of winnings.
Part two
For part two, we don't have to change much. We have to adjust our Card representation, switching ‘J’ from Jack to Joker and the corresponding value. We also have to adjust our Hand analysis routine.
During the Hand analysis, we have to consider the number of Jokers. If this weren’t a one-of, creating an encoding or storing the logic in a matrix would make sense. Again, I just spelled out all the logic in the code.
And we can put this together.
Conclusion
How did you do with today’s problems? Did you take the time to hide the analysis logic in a matrix/encoding?
Share your solutions and insights. Check out the repository with solutions and links to all articles: https://github.com/HappyCerberus/aoc-2023-cpp-solutions.
for part 2 my approach with dealing with the jokers is to add the number of jokers to `freq[0]` and analyze the hand similar to how it is done in part 1