Daily bit(e) of C++ | Advent of Code: Day 4
Daily bit(e) of C++ #337, Advent of Code 2023 using Modern C++: Day 4.
Welcome to day 4 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/4.
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.
Today, we are analyzing winning scratchcards.
Part one
Our goal is to return the total sum of scores; we can, therefore, build functionality to analyze a single line and then accumulate the results for all lines.
Let’s first consider how we can determine the score. Fundamentally, we want to find the intersection between the first list of numbers and the second. The fastest way to achieve that is to sort both parts and then use the set_intersection algorithm.
However, for that, we need to have both lists of numbers as integers in a container.
Due to the simple format, we can parse the line fully using views. First, we need to get rid of the prefix using drop_while and drop, then we can split the line into two chunks using split, which also gets rid of the delimiter, and then finally, we can extract the numbers using spanstream, views::stream and the copy algorithm.
Part two
Interestingly, we can reuse most of the above functionality for part two. We still need to analyze each scratchcard; however, instead of score, we return the number of matches.
The processing logic where we get more cards might seem complex. However, it boils down to the following: for each card c, add “copies of c” copies to each card in the range [c,c+“number of matches on c”).
Besides the calculated number of matches, we also need to keep track of the number of copies (we start with one copy of each card), and once we have processed the cards using the above logic, we return the sum of copies across all cards.
Conclusion
How did you do with today’s problems? Did you find it easier than yesterday?
Share your solutions and insights. Check out the repository with solutions and links to all articles: https://github.com/HappyCerberus/aoc-2023-cpp-solutions.