Modern C++ in Advent of Code: Day 5
On the fifth day of Advent Of Code, we are tasked to simulate a crane reordering crates. I recommend you try to solve the problems yourself: https://adventofcode.com
Input
The main complexity of today's problem is actually in input parsing, so for the first time, let’s have a look at the parsing code. For simple processing, it would be convenient to have the state represented as std::vector<std::vector<char>>
.
The input is inconveniently irregular with significant whitespace. The simplest way to parse such input in C++ is first to parse by-line and then interpret each line.
Unlike the initial state, the orders are regular, so we can introduce a custom type and overload the stream extraction operator.
Part1: CrateMover 9000
For part one, we can now process each order, modifying the state as we go.
We could move crates one by one; however, we can also move all crates with one std::ranges::copy
, which is arguably simpler. Either way, we must remember to remove the crates from the source.
Part2: CrateMover 9001
For part two, we can re-use the same code, with the caveat that now we copy the crates in order.
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.