Daily bit(e) of C++ | Advent of Code: Day 14
Daily bit(e) of C++ #347, Advent of Code using Modern C++: Day 14.
Welcome to day 14 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/14.
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 shifting the positions of parabolic mirrors.
Part one
After reading part one, I wasn’t quite sure which part two would go, so I implemented a custom logic to calculate the weight. You could (and should) apply the logic from part two to part one. The only benefit of this custom logic is that it doesn't modify the input.
However, just for completeness. We can calculate the weight after shifting all mirrors north by scanning top to bottom, remembering the last positions ‘#’ and the sizes of stacks of ‘O’ that would be caused if the mirrors were shifted north.
Part two
Because our goal is to determine the weight after 1000000000 cycles, it is clear that we cannot iterate over all these cycles, meaning that there has to be a loop. If there is a loop, the only way to detect it is to remember the previously visited states, meaning we must simulate the cycles.
We can start by implementing a routine for shifting a single line to the left (i.e. west).
Now, for the C++ ranges magic trick. We can use this one lambda to shift in all four directions. All we have to do is to invoke it on top of the appropriate view.
With the heavy lifting finished, we now have to iterate until we revisit a previous state, then round the iterations until we are at a clean loop multiple (i.e., the same state we would be after 1000000000 iterations) and calculate the weight.
Conclusion
How did you do with today’s problems? Did you correctly guess where the second part was going to go?
Share your solutions and insights. Check out the repository with solutions and links to all articles: https://github.com/HappyCerberus/aoc-2023-cpp-solutions.