Advertisement
Guest User

Advent of Code 2021 Day 2

a guest
Dec 2nd, 2021
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. from typing import Generator, Literal
  2.  
  3.  
  4. Direction = Literal['forward', 'up', 'down']
  5. Distance = int
  6. Instruction = tuple[Direction, Distance]
  7.  
  8.  
  9. def parse_directions(filepath) -> Generator[Instruction, None, None]:
  10.     with open(filepath, 'r') as f:
  11.         for line in f:
  12.             direction, distance = line.split()
  13.             yield direction, int(distance)
  14.  
  15.  
  16. class Submarine_v1:
  17.     def __init__(self) -> None:
  18.         self.depth = 0
  19.         self.horizontal_position = 0
  20.  
  21.     def navigate(self, instruction: Instruction) -> None:
  22.         match instruction:
  23.             case ("forward", forward_distance):
  24.                 self.horizontal_position += forward_distance
  25.             case ("down", depth_down):
  26.                 self.depth += depth_down
  27.             case ("up", depth_up):
  28.                 self.depth -= depth_up
  29.  
  30.  
  31. class Submarine_v2:
  32.     def __init__(self) -> None:
  33.         self.depth = 0
  34.         self.horizontal_position = 0
  35.         self.aim = 0
  36.  
  37.     def navigate(self, instruction: Instruction) -> None:
  38.         match instruction:
  39.             case ("forward", forward_distance):
  40.                 self.horizontal_position += forward_distance
  41.                 self.depth += self.aim * forward_distance
  42.             case ("down", aim_down):
  43.                 self.aim += aim_down
  44.             case ("up", aim_up):
  45.                 self.aim -= aim_up
  46.  
  47.  
  48. def part_a():
  49.     fp = r"data/day02.txt"
  50.     submarine = Submarine_v1()
  51.     for instruction in parse_directions(fp):
  52.         submarine.navigate(instruction)
  53.     return submarine.depth * submarine.horizontal_position
  54.  
  55.  
  56. def part_b():
  57.     fp = r"data/day02.txt"
  58.     submarine = Submarine_v2()
  59.     for instruction in parse_directions(fp):
  60.         submarine.navigate(instruction)
  61.     return submarine.depth * submarine.horizontal_position
  62.  
  63.  
  64. if __name__ == '__main__':
  65.     print(part_a())
  66.     print(part_b())
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement