Modern C++ in Advent of Code: Day 2

Šimon Tóth
2 min readDec 2, 2022

--

It is the second day of Advent of Code. Today, we will use our C++ powers to calculate scores in a Rock-Paper-Scissors tournament. I recommend you try to solve the problems yourself: https://adventofcode.com/.

Input

Our input is a series of pairs of the opponent's move and our response. The opponent's move is encoded into the characters A, B and C, representing Rock, Paper, and Scissors respectively. Our response is encoded in a similar fashion into characters X, Y and Z. We will take this input as std::vector<std::pair<char,char>>.

Part1: the response encodes our move

In this part our goal is to interpret our response as a move, meaning that X, Y and Z correspond to Rock, Paper, and Scissors respectively.

The first step is to normalize the input:

  • oponent-'A' will translate Rock into 0, Paper to 1 and Scissors to 2
  • our_move-'X' will translate Rock into 0, Paper to 1 and Scissors to 2

While the C++ standard doesn’t specify the character encoding, it does require that the letters are encoded as consecutive values.

To calculate the scores, we need one more observation. A move beats another if it is one rank higher than the opposing move. E.g. Paper (1) beats Rock (0). There is one caveat here Rock (0) beating Scissors (2), which is why we will need to use modulo in our calculation.

Putting this together, we end up with the following solution:

Part2: the response encodes the match result

For part two, we can use the same logic, except, instead of calculating the match result, we are given the match result and we need to calculate our move.

As in part one, our move needs to be either one rank higher or one rank lower than the opponent's move to get a win or a loss.

Putting this together, we end up with the following solution:

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.

--

--

Šimon Tóth

20 years worth of Software Engineering experience distilled into easily digestible articles.