Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

Advent of Code - 2022

This is a solution to Day 2 of Advent of Code 2022.

Day 2 - Rock Paper Scissors

The Elves begin to set up camp on the beach. To decide whose tent gets to be closest to the snack storage, a giant Rock Paper Scissors tournament is already in progress.

Rock Paper Scissors is a game between two players. Each game contains many rounds; in each round, the players each simultaneously choose one of Rock, Paper, or Scissors using a hand shape. Then, a winner for that round is selected: Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock. If both players choose the same shape, the round instead ends in a draw.

Appreciative of your help yesterday, one Elf gives you an encrypted strategy guide (your puzzle input) that they say will be sure to help you win. "The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second column--" Suddenly, the Elf is called away to help with someone's tent.

The second column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. Winning every time would be suspicious, so the responses must have been carefully chosen.

The winner of the whole tournament is the player with the highest score. Your total score is the sum of your scores for each round. The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won).

Since you can't be sure if the Elf is trying to help you or trick you, you should calculate the score you would get if you were to follow the strategy guide.

For example, suppose you were given the following strategy guide:

A Y
B X
C Z

This strategy guide predicts and recommends the following:

  • In the first round, your opponent will choose Rock (A), and you should choose Paper (Y). This ends in a win for you with a score of 8 (2 because you chose Paper + 6 because you won).
  • In the second round, your opponent will choose Paper (B), and you should choose Rock (X). This ends in a loss for you with a score of 1 (1 + 0).
  • The third round is a draw with both players choosing Scissors, giving you a score of 3 + 3 = 6.

In this example, if you were to follow the strategy guide, you would get a total score of 15 (8 + 1 + 6).

Read input

For reading input today, I'll start by defining some data structures.

First one will be RPSScore (short for Rock-Paper-Scissors Score) which is an IntEnum. Enums are great when you want to give descriptive names to individual values and by using subclass IntEnum, we can do maths with the results directly with the enums.

Here I decided to give each Enum member the value that is its score in the final calculation. That way, when calculating the score, I can calculate win/draw/loss score + the enum member and get the final score.

Second data structure is another IntEnum, this time for the score for match output. Loss gains the player 0, draw 3 and win 6 points.

Third data structure is input_to_RPS which maps each input (A, B, C, X, Y, Z) to its corresponding Enum member.

from enum import IntEnum

from utils import read_input


class RPSScore(IntEnum):
    ROCK = 1
    PAPER = 2
    SCISSORS = 3
    
class MatchScore(IntEnum):
    LOSS = 0
    DRAW = 3
    WIN = 6
    
input_to_RPS = {
    "A": RPSScore.ROCK,
    "B": RPSScore.PAPER,
    "C": RPSScore.SCISSORS,
    "X": RPSScore.ROCK,
    "Y": RPSScore.PAPER,
    "Z": RPSScore.SCISSORS
}

def transformer(line):
    opponent, player = line.split(' ')
    return [input_to_RPS[player], input_to_RPS[opponent]]

example_strategy = read_input(2, transformer, True)
strategy = read_input(2, transformer)

Calculating the score

Last summer I wrote a blog post about writing unit tests in Jupyter Notebooks so when I was building this scoring function, I wanted to make sure I calculated all the cases correctly and decided to use doctest.

In my blog post, I said that doctest is good for simple functions but gets out of hand real fast. I think this is a perfect example of that. With just 9 different cases, the docstring becomes 20 lines long and not that easy to read and follow. But it works and having tests made me not run into harder-to-debug issues down the line.

The scoring uses Python's pattern matching, available in Python since 3.10 and a few nice features of it:

  1. For the first clause, it uses a guard in the form of a if statement that matches to any two inputs as long as they are the same.
  2. For the second clause, it uses the "or" functionality, matching to any of the cases where player wins
  3. It uses the default case for anything else

And a nice benefit of defining our scores in enums earlier, we don't see a single number in this function. That means we don't need to know the exact values in this function, leading to less errors if they would change in the future for example.

In this case, as this function is the only one today that has doctests, I'm running the test suite immediately in the same code block but it's important to note that it will run all the doctests in the file/notebook so sometimes it makes sense to run as its own block or at the end of the file.

def score_round(player, opponent):
    """
    >>> score_round(RPSScore.ROCK, RPSScore.ROCK)
    4
    >>> score_round(RPSScore.PAPER, RPSScore.PAPER)
    5
    >>> score_round(RPSScore.SCISSORS, RPSScore.SCISSORS)
    6
    >>> score_round(RPSScore.ROCK, RPSScore.PAPER)
    1
    >>> score_round(RPSScore.ROCK, RPSScore.SCISSORS)
    7
    >>> score_round(RPSScore.PAPER, RPSScore.ROCK)
    8
    >>> score_round(RPSScore.PAPER, RPSScore.SCISSORS)
    2
    >>> score_round(RPSScore.SCISSORS, RPSScore.ROCK)
    3
    >>> score_round(RPSScore.SCISSORS, RPSScore.PAPER)
    9
    """
    match [player, opponent]:
        case [player, opponent] if player == opponent:
            return MatchScore.DRAW + player
        case ([RPSScore.ROCK, RPSScore.SCISSORS] |
              [RPSScore.PAPER, RPSScore.ROCK] | 
              [RPSScore.SCISSORS, RPSScore.PAPER]):
            return MatchScore.WIN + player
        case _:
            return MatchScore.LOSS + player
        
import doctest

doctest.testmod()

Part 1

What would your total score be if everything goes exactly according to your strategy guide?

To calculate the total score, we run all the plays from the strategy and pass them to score_round using the * operator that unpacks the elements of an iterator, in this case a list of two, into separate arguments for the function.

score = sum(score_round(*plays) for plays in strategy)
print(f'Part 1: {score}')
assert score == 12740

Part 2

The Elf finishes helping with the tent and sneaks back over to you. "Anyway, the second column says how the round needs to end: X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. Good luck!"

The total score is still calculated in the same way, but now you need to figure out what shape to choose so the round ends as indicated. The example above now goes like this:

  • In the first round, your opponent will choose Rock (A), and you need the round to end in a draw (Y), so you also choose Rock. This gives you a score of 1 + 3 = 4.
  • In the second round, your opponent will choose Paper (B), and you choose Rock so you lose (X) with a score of 1 + 0 = 1.
  • In the third round, you will defeat your opponent's Scissors with Rock for a score of 1 + 6 = 7.

Now that you're correctly decrypting the ultra top secret strategy guide, you would get a total score of 12.

I think this might be the first time in my Advent of Code solving era where the second part actually changes the input reading instead of just the solution.

Now, instead of parsing two plays, we get a play and a result and using the previous enums and scoring function, need to add a bit to figure out the right play.

I originally had a dictionary with tuples like ('A', 'X') leading to a RPSScore value but I felt that the readability wasn't great as following along what 'A' or 'X' means is hard. So I refactored that into a function that uses RPSScore and MatchScore enums for improved readability.

In pick_play function, we don't care about the integer value MatchScore members map to, they are just a representation of a result of a match. From a functional stand point, they are an alias to make it easier for developers to understand what the variables mean.

def pick_play(opponent, desired_result):
    return {
        (RPSScore.ROCK, MatchScore.LOSS): RPSScore.SCISSORS,
        (RPSScore.ROCK, MatchScore.DRAW): RPSScore.ROCK,
        (RPSScore.ROCK, MatchScore.WIN): RPSScore.PAPER,
        
        (RPSScore.PAPER, MatchScore.LOSS): RPSScore.ROCK,
        (RPSScore.PAPER, MatchScore.DRAW): RPSScore.PAPER,
        (RPSScore.PAPER, MatchScore.WIN): RPSScore.SCISSORS,
        
        (RPSScore.SCISSORS, MatchScore.LOSS): RPSScore.PAPER,
        (RPSScore.SCISSORS, MatchScore.DRAW): RPSScore.SCISSORS,
        (RPSScore.SCISSORS, MatchScore.WIN): RPSScore.ROCK
    }[(opponent, desired_result)]

results = {
    'X': MatchScore.LOSS,
    'Y': MatchScore.DRAW,
    'Z': MatchScore.WIN
}

def part2_transformer(line):
    opponent, result = line.split(' ')
    opponent = moves[opponent]
    desired_result = results[result]
    player = pick_play(opponent, desired_result)
    return player, opponent
    

part2_example_strategy = read_input(2, part2_transformer, True)
part2_strategy = read_input(2, part2_transformer)

Following the Elf's instructions for the second column, what would your total score be if everything goes exactly according to your strategy guide?

The actual scoring calculation is exactly the same as in part 1 as the only change needed to be made was into how we parse the strategy guide.

part2_score = sum(score_round(*plays) for plays in part2_strategy)
print(f'Part 2: {part2_score}')
assert part2_score == 11980