From 228f7501bb194e591e0f96f624a05c3c91bce0b1 Mon Sep 17 00:00:00 2001 From: Mikael CAPELLE Date: Fri, 2 Dec 2022 15:06:37 +0100 Subject: [PATCH] More comments. --- 2022/day2.py | 40 ++++++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/2022/day2.py b/2022/day2.py index 304c37d..132654e 100644 --- a/2022/day2.py +++ b/2022/day2.py @@ -2,6 +2,13 @@ from pathlib import Path +# the solution relies on replacing rock / paper / scissor by values 0 / 1 / 2 and using +# modulo-3 arithmetic +# +# in modulo-3 arithmetic, the winning move is 1 + the opponent move (e.g., winning move +# if opponent plays 0 is 1, or 0 if opponent plays 2 (0 = (2 + 1 % 3))) +# + # we read the lines in a Nx2 in array with value 0/1/2 instead of A/B/C or X/Y/Z for # easier manipulation with open(Path(__file__).parent.joinpath("inputs", "day2.txt")) as fp: @@ -11,17 +18,34 @@ with open(Path(__file__).parent.joinpath("inputs", "day2.txt")) as fp: def score_1(ux: int, vx: int) -> int: - # explanation: - # - (1 + vx) is just the score of the shape - # - ((1 - (ux - vx)) % 3) gives 0 for loss, 1 for draw and 2 for win, that we - # can multiply with 3 to get the outcome score - return (1 + vx) + ((1 - (ux - vx)) % 3) * 3 + # here ux and vx are both moves: 0 = rock, 1 = paper, 2 = scissor + # + + # 1. to get the score of the move/shape, we simply add 1 -> vx + 1 + # 2. to get the score of the outcome (loss/draw/win), we use the fact that the + # winning hand is always the opponent hand (ux) + 1 in modulo-3 arithmetic: + # - (ux - vx) % 3 gives us 0 for a draw, 1 for a loss and 2 for a win + # - 1 - ((ux - vx) % 3) gives us -1 for a win, 0 for a loss and 1 for a draw + # - (1 - ((ux - vx) % 3)) gives us 0 / 1 / 2 for loss / draw / win + # - the above can be rewritten as ((1 - (ux - vx)) % 3) + # we can then simply multiply this by 3 to get the outcome score + # + return (vx + 1) + ((1 - (ux - vx)) % 3) * 3 def score_2(ux: int, vx: int) -> int: - # explanation: - # - (ux + vx - 1) % 3 gives the target shape (0, 1, 2), we add one to get the score - # - vx * 3 is simply the outcome score + # here ux is the opponent move (0 = rock, 1 = paper, 2 = scissor) and vx is the + # outcome (0 = loss, 1 = draw, 2 = win) + # + + # 1. to get the score to the move/shape, we need to find it (as 0, 1 or 2) and then + # add 1 to it + # - (vx - 1) gives the offset from the opponent shape (-1 for a loss, 0 for a + # draw and 1 for a win) + # - from the offset, we can retrieve the shape by adding the opponent shape and + # using modulo-3 arithmetic -> (ux + vx - 1) % 3 + # - we then add 1 to get the final shape score + # 2. to get the score of the outcome, we can simply multiply vx by 3 -> vx * 3 return (ux + vx - 1) % 3 + 1 + vx * 3