Modern C++ in Advent of Code: Day 22
On day twenty-two of Advent of Code, we are following the notes from monkeys as we try to uncover a password.
I do encourage you to try to solve it yourself first https://adventofcode.com.
Input
Our input today comes in two parts, first a map that we will take as std::vector<std::string>
and then the notes from monkeys that we will take as std::string
.
Exploration with wrap-around
For part one, we need to follow the notes from the monkeys to move around the map.
There are two main complications. Our directions are relative; we are only directed to move forward and turn left and right. We can encapsulate this logic in a Direction
class.
The second complication is that the map wraps around. If we step out of bounds or on an empty space, we wrap around in that row or column. Because of the shape of the map, the simplest approach is to encapsulate the logic in functions that return the leftmost, rightmost, topmost and bottommost positions from a particular coordinate.
We could cache or pre-calculate these values for performance, but that isn’t necessary today.
Putting this together, we adjust our position based on the current direction at each step. If we are out of bounds, we wrap around using our functions, avoiding walls.
To calculate the password, we need to follow the instructions, repeatedly moving or turning left and right.
It’s a CUBE!
For part two, we now need to interpret the map as sides of a cube.
This mainly changes the wrap-around logic, as now, when we exit a side, we not only change our position but can also change our direction.
I hard-coded my solution to the particular pattern of sides in my input. The main idea here is to split the input into numbered sides of the cube and, for each side, configure four functions that represent the wrap-around logic in each of the four directions we can leave that side.
I made a physical cube to help me with the mapping.
All this is supported by a new position type that encodes the tile we are on, the relative position within that tile and finally, the direction.
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.