Advertisement
Guest User

Advent of Code Day 15

a guest
Dec 15th, 2020
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. """Day 15 of Advent of Code 2020 Solution"""
  2. from collections import defaultdict, deque
  3.  
  4.  
  5. class RambunctiousRecitation:
  6.     def __init__(self, starting_numbers: str):
  7.         self.starting_numbers: deque[int] = deque(
  8.             [int(n) for n in starting_numbers.split(",")]
  9.         )
  10.         self.current_turn: int = 0
  11.         self.last_seen: defaultdict[int, deque[int, int]] = defaultdict(
  12.             lambda: deque([0, 0], maxlen=2)
  13.         )
  14.         self.last_spoken = None
  15.         self.seen: set[int] = set()
  16.  
  17.     def __next__(self):
  18.         self.current_turn += 1
  19.         if self.starting_numbers:
  20.             spoken = self.starting_numbers.popleft()
  21.             self.last_seen[spoken].appendleft(self.current_turn)
  22.             self.last_spoken = spoken
  23.             return
  24.         if self.last_seen[self.last_spoken][-1] == 0:
  25.             self.last_spoken = 0
  26.             self.last_seen[self.last_spoken].appendleft(self.current_turn)
  27.         else:
  28.             self.last_spoken = (
  29.                 self.last_seen[self.last_spoken][0]
  30.                 - self.last_seen[self.last_spoken][-1]
  31.             )
  32.             self.last_seen[self.last_spoken].appendleft(self.current_turn)
  33.  
  34.  
  35. def find_nth_number(starting_numbers: str, nth_number: int) -> int:
  36.     rr = RambunctiousRecitation(starting_numbers)
  37.     for _ in range(nth_number):
  38.         next(rr)
  39.     return rr.last_spoken
  40.  
  41.  
  42. def part_a(file_location):
  43.     with open(file_location, "r") as f:
  44.         data = f.readline().strip()
  45.     return find_nth_number(data, 2020)
  46.  
  47.  
  48. def part_b(file_location):
  49.     with open(file_location, "r") as f:
  50.         data = f.readline().strip()
  51.     return find_nth_number(data, 30000000)
  52.  
  53.  
  54. if __name__ == "__main__":
  55.     file_location = r"data\day15.txt"
  56.     print(part_a(file_location))
  57.     print(part_b(file_location))
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement