Advertisement
Guest User

Advent of Code Day 23

a guest
Dec 23rd, 2020
580
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. """Day 23 of Advent of Code 2020 Solution"""
  2.  
  3.  
  4. def cup_io(file_location):
  5.     with open(file_location, "r") as f:
  6.         cups = [int(i) for i in f.readline().strip()]
  7.     return cups
  8.  
  9.  
  10. class CrabCups:
  11.     def __init__(self, cups):
  12.         self.current = cups[0]
  13.         self.next_cup = {}
  14.         for i, c in enumerate(cups, 1):
  15.             try:
  16.                 self.next_cup[c] = cups[i]
  17.             except IndexError:
  18.                 self.next_cup[c] = cups[0]
  19.  
  20.     def __iter__(self):
  21.         return self
  22.  
  23.     def __next__(self):
  24.         remove = []
  25.         to_move = self.current
  26.         for i in range(3):
  27.             remove.append(self.next_cup[to_move])
  28.             to_move = self.next_cup[to_move]
  29.         self.next_cup[self.current] = self.next_cup[remove[2]]
  30.         destination = self.current - 1
  31.         while destination <= 0 or destination in remove:
  32.             if destination == 0:
  33.                 destination = len(self.next_cup)
  34.             if destination in remove:
  35.                 destination -= 1
  36.         self.next_cup[destination], self.next_cup[remove[2]] = (
  37.             remove[0],
  38.             self.next_cup[destination],
  39.         )
  40.         self.current = self.next_cup[self.current]
  41.  
  42.     @property
  43.     def final(self):
  44.         current = 1
  45.         output = []
  46.         for _ in range(len(self.next_cup) - 1):
  47.             output.append(self.next_cup[current])
  48.             current = self.next_cup[current]
  49.         output = [str(n) for n in output]
  50.         return "".join(output)
  51.  
  52.  
  53. def part_a(file_location):
  54.     cups = cup_io(file_location)
  55.     cc = CrabCups(cups)
  56.     for _ in range(100):
  57.         next(cc)
  58.     return cc.final
  59.  
  60.  
  61. def part_b(file_location):
  62.     cups = cup_io(file_location)
  63.     cups.extend(range(10, 1000001))
  64.     cc = CrabCups(cups)
  65.     for i in range(10000000):
  66.         next(cc)
  67.     a = cc.next_cup[1]
  68.     b = cc.next_cup[a]
  69.     return a * b
  70.  
  71.  
  72. if __name__ == "__main__":
  73.     file_location = r"data\day23.txt"
  74.     print(part_a(file_location))
  75.     print(part_b(file_location))
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement