Modern C++ in Advent of Code: Day 9
On day nine of Advent of Code, we are simulating the movements of a rope.
I do encourage you to try to solve it yourself first https://adventofcode.com.
Input
Today’s input is a series of movement orders. We will introduce a custom data structure to represent each order, which allows us to overload the stream extraction operator to read each order.
With that, we can use a simple std::views::istream
and end up with a std::vector<Order>
as our input.
Simulating a short rope
In part one, we are tasked with simulating a short rope consisting of a head and tailpiece. The head follows the directions of the orders, moving in orthogonal directions, and the tail needs to stay at most one space away (orthogonal or diagonal) and can move diagonally.
All we need to keep track of is the head and the tail positions and a set of positions that the tail visited during the simulation (this is our output).
We can then decompose the problem into “move the head” and “follow with the tail”, which we will repeat until we have processed each order.
Simulating a long rope
In part two, we are now tasked to improve the simulation by simulating a rope that consists of ten pieces (head, eight intermediate and the tail).
This doesn’t change our approach, with one important caveat. While the head only moves orthogonally, the intermediate pieces can move diagonally. Our “follow with the tail” routine must account for this.
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.