Modern C++ in Advent of Code: Day 23
It is day twenty-three of Advent of Code and we are simulating optimal planting patterns for the starfruit trees.
I do encourage you to try to solve it yourself first https://adventofcode.com.
Input
Today’s input is our initial elf configuration. We will store this information in our custom Map
type.
Decomposing the problem
Our task has several moving pieces, so let’s first think about how to decompose the problem into smaller pieces that can be easily implemented in isolation.
First, for the main loop, we will need to iterate over all elves, have them plan their move and if they are the only elf with that destination, move them in the second part of the loop. This logic will be encapsulated in our main Elves
class.
Second, to determine where an elf can move, they must check whether a specific space is already occupied. For that, we need some map representation. Notably, while the area covered by the elves will change as we run our simulation, the number of elves will not. This points to sparse storage. We will encode this in our Map
class that will provide helper functions for adding, moving and querying elf positions.
Finally, we have the complication of rotating elf logic. In each round, the directional preference of elves changes in a circular pattern. While this is not data but logic, that means little to our C++ powers. We can encode this as an iteration over a std::vector
of std::function
, with an offset that increments after each round.
With all the pieces ready, all we need is to implement all the logic 😀.
Links
The repository with a complete solution (including input parsing) is available here: https://github.com/HappyCerberus/moderncpp-aoc-2022.
I post daily Modern C++ content on Twitter, LinkedIn, Mastodon, Medium and Substack.