= str.maketrans("ABCXYZ", "RPSRPS", " ")
RPS_CODE def rps_decode(data: str) -> str:
return str.translate(data, RPS_CODE)
day2
AoC Day2: Rock Paper Scissors
Decode the elf’s RPS strategy and score the game. Strategy data will be in two columns like:
A Y
B X
C Z
This strategy guide predicts opponent will play Rock (A), then Paper (B), then Scissors (C). It recommends you play: * Paper (Y) two win with score of 2 for Paper + 6 for win = 8. * Rock (X) with score of 1 for Rock + 0 for loss = 1. * Scissors (Z) for score of 3 for Scissors + 3 for draw = 6. * Total Score = 15
Solution sketch:
- Read the file
- Replace {A,X} -> Rock, {B,Y} -> Paper, {C,Z} -> Scissors
- Move scores: Rock=1, Paper=2, Scissors=3
- Win scores: Loss=0, Draw=3, Win=6
- Score each round, sum
Part 1
Get the data
Decode both moves to R, P, S. Keep as a two-letter string like “RP”.
with open("../data/day2_input.txt") as f:
= [x.strip()
data
.translate(RPS_CODE)for x in f.readlines()]
5] data[:
['PP', 'SS', 'SP', 'SP', 'RR']
Define the scoring
score_strategy
score_strategy (strategy:list[str])
score_round
score_round (moves:str)
Test using the example
assert score_round("RP") == 8 # win + 2
assert score_round("RR") == 4 # draw + 1
assert score_round("RS") == 3 # lose + 3
= ["A Y", "B X", "C Z"]
test = [x.translate(RPS_CODE) for x in test]
test assert [score_round(x) for x in test] == [8, 1, 6]
assert score_strategy(test) == 15
Run on the data
score_strategy(data)
11841
Part 2
No wait! We had it wrong. The code is really:
X : You must lose
Y : You must draw
Z : You must win
All else is the same, so the example is now:
A Y -> RR -> Draw -> 1 + 3 = 4
B X -> PR -> Lose -> 1 + 0 = 1
C Z -> SR -> Win -> 1 + 6 = 7
--
12
We have to change rps_decode
because our moves now depend on theirs.
Redefine the coding
get_plan
get_plan (strat:str)
Return dict of resposes for 1-letter strat
rps_decode
rps_decode (code:str)
Convert coded ‘A X’ type string to ‘RS’ type string.
Test using example
= ["A Y", "B X", "C Z"]
test = [rps_decode(x) for x in test]
test assert [score_round(x) for x in test] == [4, 1, 7]
assert score_strategy(test) == 12
Run on data
with open("../data/day2_input.txt") as f:
= [rps_decode(x.strip()) for x in f.readlines()]
data score_strategy(data)
13022