Skip to content

Instantly share code, notes, and snippets.

@horvatha
Last active February 15, 2023 11:16
Show Gist options
  • Save horvatha/830f8f690c15394c156c2f9359c8e6ab to your computer and use it in GitHub Desktop.
Save horvatha/830f8f690c15394c156c2f9359c8e6ab to your computer and use it in GitHub Desktop.
"""
Solution for
https://adventofcode.com/2022/day/2
first and second half
"""
from typing import List, Callable
RESULT_SCORES = {"draw": 3, "win": 6, "loose": 0}
OBJECT_SCORES = {"Rock": 1, "Paper": 2, "Scissors": 3}
OPPONENTS_OBJECTS = {"A": "Rock", "B": "Paper", "C": "Scissors"}
WHAT_WINS_AGAINST_THAT = {"Rock": "Paper", "Paper": "Scissors", "Scissors": "Rock"}
RESULT_DICT = {
"Y": "draw",
"Z": "win",
"X": "loose",
}
# First half's scores
def winning_score1(pair: str) -> int:
result_dict = {
"draw": {"A X", "B Y", "C Z"},
"win": {"A Y", "B Z", "C X"},
"loose": {"A Z", "B X", "C Y"},
}
result = None
for k, v in result_dict.items():
if pair in v:
result = k
assert isinstance(result, str)
return RESULT_SCORES[result]
def chosen_score1(pair: str) -> int:
code = pair[2]
chosen_object = {"X": "Rock", "Y": "Paper", "Z": "Scissors"}
return OBJECT_SCORES[chosen_object[code]]
# Second half's scores
def winning_score2(pair: str) -> int:
return RESULT_SCORES[RESULT_DICT[pair[2]]]
def chosen_score2(pair: str) -> int:
opponent_code, result_code = pair.split()
opponents_object = OPPONENTS_OBJECTS[opponent_code]
result = RESULT_DICT[result_code]
if result == "draw":
my_choice = opponents_object
if result == "win":
my_choice = WHAT_WINS_AGAINST_THAT[opponents_object]
if result == "loose":
what_does_it_wins_against = {v: k for k, v in WHAT_WINS_AGAINST_THAT.items()}
my_choice = what_does_it_wins_against[opponents_object]
return OBJECT_SCORES[my_choice]
def sum_score(pairs: List[str], winning_score: Callable, chosen_score: Callable) -> int:
return sum(winning_score(pair) + chosen_score(pair) for pair in pairs)
def main():
with open("input.txt") as f:
pairs = [line.strip() for line in f]
print(sum_score(pairs, winning_score1, chosen_score1))
print(sum_score(pairs, winning_score2, chosen_score2))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment