Advertisement
hhoppe

Advent of code 2021 day 18

Dec 18th, 2021
1,425
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. def parse_snail(line):
  2.   return eval(line)  # Unsafe.
  3.  
  4. def explode_one(snail) -> bool:
  5.  
  6.   def add_to_middle(snail, side, value):
  7.     side1 = 1 - side
  8.     while not isinstance(snail[side], int):
  9.       snail = snail[side]
  10.       side = side1
  11.     snail[side] += value
  12.  
  13.   def recurse(snail, depth=0):
  14.     for i, child in enumerate(snail):
  15.       if not isinstance(child, int):
  16.         if depth == 3:
  17.           snail[i] = 0
  18.           add_to_middle(snail, 1 - i, child[1 - i])
  19.           child[1 - i] = None
  20.           return True, child
  21.         done, left_right = recurse(child, depth + 1)
  22.         if done:
  23.           if left_right[1 - i] is not None:
  24.             add_to_middle(snail, 1 - i, left_right[1 - i])
  25.             left_right[1 - i] = None
  26.           return done, left_right
  27.     return False, [None, None]
  28.  
  29.   return recurse(snail)[0]
  30.  
  31. def split_one(snail) -> bool:
  32.   for i, child in enumerate(snail):
  33.     if isinstance(child, int):
  34.       if child >= 10:
  35.         snail[i] = [child // 2, (child + 1) // 2]
  36.         return True
  37.     elif split_one(snail[i]):
  38.       return True
  39.   return False
  40.  
  41. def reduce_snail(snail):
  42.   while explode_one(snail) or split_one(snail):
  43.     pass
  44.   return snail
  45.  
  46. def magnitude(snail):
  47.   return (snail if isinstance(snail, int) else
  48.           3 * magnitude(snail[0]) + 2 * magnitude(snail[1]))
  49.  
  50. def process1(s, part2=False):
  51.   lines = s.strip('\n').split('\n')
  52.   snails = [parse_snail(line) for line in lines]
  53.  
  54.   if not part2:
  55.     snail = snails[0]
  56.     for i in range (1, len(snails)):
  57.       snail = reduce_snail([snail, snails[i]])
  58.     return magnitude(snail)
  59.  
  60.   return max(magnitude(reduce_snail(copy.deepcopy([snail0, snail1])))
  61.              for snail0, snail1 in itertools.permutations(snails, 2))
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement