Modern C++ in Advent of Code: Day 10
It is day ten of Advent of Code, and we are simulating a simple CPU.
I do encourage you to try to solve it yourself first https://adventofcode.com.
Input
Today’s input is a series of instructions with arguments.
The solution I will present is a bit overengineered as I was betting on more instructions in part two. A more straightforward solution (notably for only two instructions) would be to decode the two-cycle add into a no-op and a single-cycle add, allowing us to represent the input as a vector of single-cycle lambdas.
We can represent each instruction using a custom type and then store all instructions as a std::vector<std::variant<InstrNoop,InstrAdd>>
. This has the benefit of separating the decoding of arguments into the corresponding instruction.
Running the program
For part one, we need to sum up the values of the register X (multiplied by the number of cycles) at specific times.
For part two, we need to interpret the value of the register X as a sprite that either leads to a pixel being on or off at each cycle as we scan over pixels of an output screen.
We can do both within our cycle loop, with the instructions actuating at the end of each cycle.
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.