Table of Contents
Challenge – Part 1
https://adventofcode.com/2022/day/2
Example
For example, suppose you were given the following strategy guide:
A Y
B X
C ZThis 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).
Solution
The first step is to take in the sample data and split at the newline to get the individual rounds:
data = """A Y
B X
C Z"""
def test_split_data():
rounds = data.split("\n")
assert rounds == ['A Y', 'B X', 'C Z']
Than I came up with the idea to create a dictionary with all possible constellations and the appropriate scores:
strategy_dict = {
'A X': 4, # 1 + 3
'A Y': 8, # 2 + 6
'A Z': 3, # 3 + 0
'B X': 1, # 1 + 0
'B Y': 5, # 2 + 3
'B Z': 9, # 3 + 6
'C X': 7, # 1 + 6
'C Y': 2, # 2 + 0
'C Z': 6, # 3 + 3
}
After that we iterate over all rounds and sum up the scores. For the sample data it worked quite nicely like this:
def test_lookup_strategy_dict():
score = 0
rounds = data.split("\n")
for round in rounds:
score += strategy_dict[round]
assert score == 15
And now the final conclusion. We read in the data from a file aoc_data_02.txt and apply the code from above:
def test_data_from_file_lookup_strategy_dict():
with open("aoc_data_02.txt", "r") as f:
data = f.read()
score = 0
rounds = data.split("\n")
for round in rounds:
score += strategy_dict[round]
assert score == 11063
This did the trick! Nice 🙂
Challenge – Part 2
Now we are confronted with a new calculation of the scores
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.
Solution
The approach with a dictionary for lookup paid out. By altering the scores for every combination of moves we can reuse the code from part 1
strategy_dict = {
'A X': 3, # 3 + 0
'A Y': 4, # 1 + 3
'A Z': 8, # 2 + 6
'B X': 1, # 1 + 0
'B Y': 5, # 2 + 3
'B Z': 9, # 3 + 6
'C X': 2, # 2 + 0
'C Y': 6, # 3 + 3
'C Z': 7, # 1 + 6
}
def test_data_from_file_lookup_strategy_dict():
with open("aoc_data_02.txt", "r") as f:
data = f.read()
score = 0
rounds = data.split("\n")
for round in rounds:
score += strategy_dict[round]
assert score == 10349
Et voilá! Day 2 is done