Advertisement
hhoppe

Advent of code 2021 day 16

Dec 16th, 2021 (edited)
814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. def process1(s, part2=False):
  2.   s = ''.join(f'{int(nibble, 16):04b}' for nibble in s.strip())
  3.   operation_for_id = {
  4.       0: lambda *operands: sum(operands),
  5.       1: lambda *operands: np.prod(operands),
  6.       2: lambda *operands: min(operands),
  7.       3: lambda *operands: max(operands),
  8.       5: lambda operand1, operand2: int(operand1 > operand2),
  9.       6: lambda operand1, operand2: int(operand1 < operand2),
  10.       7: lambda operand1, operand2: int(operand1 == operand2),
  11.   }
  12.   sum_versions = 0
  13.  
  14.   def read_bits(n):
  15.     nonlocal s
  16.     value = int(s[:n], 2)
  17.     s = s[n:]
  18.     return value
  19.  
  20.   def parse():
  21.     nonlocal sum_versions
  22.     version = read_bits(3)
  23.     sum_versions += version
  24.     id = read_bits(3)
  25.     if id == 4:
  26.       number = 0
  27.       more = True
  28.       while more:
  29.         more = read_bits(1)
  30.         number = number * 16 + read_bits(4)
  31.       return number
  32.     operands = []
  33.     length_type = read_bits(1)
  34.     if length_type == 0:
  35.       num_bits = read_bits(15)
  36.       len0 = len(s)
  37.       while len0 - len(s) != num_bits:
  38.         operands.append(parse())
  39.     else:
  40.       num_packets = read_bits(11)
  41.       for _ in range(num_packets):
  42.         operands.append(parse())
  43.     return operation_for_id[id](*operands)
  44.  
  45.   result = parse()
  46.   return result if part2 else sum_versions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement