Modern C++ in Advent of Code: Day 14
On day fourteen of Advent of Code we are simulating falling sand.
I do encourage you to try to solve it yourself first https://adventofcode.com.
Input
Today’s input is a series of scans, each scan consisting of a series of coordinates that represent connected lines. We will interpret each scan and draw the corresponding lines into our map that we store as a std::vector<std::vector<char>>
.
As we draw lines, we will also remember the bounding box (minimum and maximum coordinates drawn), which we will need for both parts.
The std::views::iota
helps us to avoid tedious index arithmetic.
Dropping sand into the void
For part one, we assume that our scans exist in a void, and we need to detect how many grains of sand will be stuck before they start falling into the void.
Since we have remembered the bounding box, we can use this to determine when a piece of sand has entered the void. Other than that, we iterate, moving the piece of sand according to the rules and detecting when it’s stuck.
Dropping sand onto the floor
For part two, we have a virtual floor, that is located two below the maximum depth coordinate, and we stop once there is a grain of sand stuck at the starting coordinate (0,500
).
We can re-use most of the solution for part one, however, instead of detecting when the sand enters the void, we detect when it gets stuck on the floor.
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.