Daily bit(e) of C++ | Advent of Code: Day 2
Daily bit(e) of C++ #335, Advent of Code 2023 using Modern C++: Day 2.
Welcome to day 2 of Advent of Code using Modern C++. Before you start reading, I highly encourage you to try to solve the two problems yourself: https://adventofcode.com/2023/day/2.
If you missed it, I have prepared a template repository for C++, with a development environment (through a devcontainer) with a bleeding edge version of the C++ toolchain: https://github.com/HappyCerberus/aoc-2023-cpp.
Our goal for today is to parse information about cubes.
Parsing
This is one of the parsing problems where C++ can struggle. The standard library facilities for parsing structured text input are not great.
However, we can make the problem easier for us by correctly decomposing. Our low-level structure is information about a cube. Each record about a cube contains the number of cubes and the colour.
Our high-level structure is information about a game. Each game starts with the prefix “Game”, followed by the game ID, followed by a “:” and then records of cubes, delimited by “,” or “;”. A game record ends with “\n” or the end of input.
We can wrap this into two data structures. Reading a record about a cube is straightforward; when reading a game, we must be careful when we report an error by setting error flags (setting an error flag means that we failed to read the record).
Part one
With the parsing finished, the solution is straightforward. We can use a std::spanstream to parse the input without conversion to std::string and then use std::views::istream to create an input range of the parsed games.
Our goal is to return the sum of game IDs, which we can achieve using std::ranges::fold_left.
Part two
We can re-use the same parsing for part two; additionally, we need to calculate the power of a game.
Conclusion
How do you find today’s problems? Did you manage to get through the parsing? Did you parse the input differently?
Share your solutions and insights. Check out the repository with solutions and links to all articles: https://github.com/HappyCerberus/aoc-2023-cpp-solutions.