Advertisement
Guest User

AoC 2022 Day 2

a guest
Dec 3rd, 2022
585
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.12 KB | None | 0 0
  1. # aoc202202.py
  2.  
  3. import pathlib
  4. import sys
  5.  
  6. # As score combinations are unique, make a lookup table for them
  7. scores: dict[str, int] = {
  8.     "AX": 4,
  9.     "AY": 8,
  10.     "AZ": 3,
  11.     "BX": 1,
  12.     "BY": 5,
  13.     "BZ": 9,
  14.     "CX": 7,
  15.     "CY": 2,
  16.     "CZ": 6,
  17. }
  18.  
  19.  
  20. def parse(puzzle_input: str) -> list[str]:
  21.     """Parse input"""
  22.     return [line.replace(' ', '') for line in puzzle_input.splitlines()]
  23.  
  24.  
  25. def part1(data: list[str]) -> int:
  26.     """Solve part 1"""
  27.     score: int = 0
  28.     for line in data:
  29.         score += scores.get(line)
  30.     return score
  31.  
  32.  
  33. def choose_strategy(play: str) -> str:
  34.     """Amend play based on XYZ
  35.    X means lose
  36.    Y means draw
  37.    Z means win"""
  38.     strategy: str = play[1]
  39.     opp_choice: str = play[0]
  40.     my_choice: str = play[1]
  41.     match strategy:
  42.         case "X":
  43.             # Play to lose
  44.             if opp_choice == "A":
  45.                 my_choice = "Z"
  46.             elif opp_choice == "C":
  47.                 my_choice = "Y"
  48.         case "Y":
  49.             # Play to draw
  50.             if opp_choice == "A":
  51.                 my_choice = "X"
  52.             elif opp_choice == "C":
  53.                 my_choice = "Z"
  54.         case "Z":
  55.             # Play to win
  56.             if opp_choice == "A":
  57.                 my_choice = "Y"
  58.             elif opp_choice == "C":
  59.                 my_choice = "X"
  60.     return opp_choice + my_choice
  61.  
  62.  
  63. def part2(data: list[str]) -> int:
  64.     """Solve part 2"""
  65.     score: int = 0
  66.     for line in data:
  67.         score += scores.get(choose_strategy(line))
  68.     return score
  69.  
  70.  
  71. def solve(puzzle_input: str) -> tuple[int, int]:
  72.     """Solve the puzzle for the given input"""
  73.     data = parse(puzzle_input)
  74.     solution1: int = part1(data)  # Correct answer was 13526 (with my data)
  75.     solution2: int = part2(data)  # Correct answer was 14204 (with my data)
  76.  
  77.     return solution1, solution2
  78.  
  79.  
  80. if __name__ == "__main__":
  81.     for path in sys.argv[1:]:
  82.         print(f"{path}:")
  83.         puzzle_input = pathlib.Path(path).read_text().strip()
  84.         solutions = solve(puzzle_input)
  85.         print("\n".join(str(solution) for solution in solutions))
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement