Advertisement
hhoppe

Advent of code 2023 day 15

Dec 15th, 2023
587
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. def day15(s, *, part2=False):
  2.   s = s.strip()
  3.  
  4.   def my_hash(s2):
  5.     # return 0 if not s2 else ((my_hash(s2[:-1]) + ord(s2[-1])) * 17) % 256
  6.     h = 0
  7.     for ch in s2:
  8.       h = ((h + ord(ch)) * 17) % 256
  9.     return h
  10.    
  11.   if not part2:
  12.     return sum(my_hash(instruction) for instruction in s.split(','))
  13.  
  14.   boxes = [[] for _ in range(256)]
  15.   for instruction in s.split(','):
  16.     label, op, focal = hh.re_groups(r'^(.+)([-=])(.*)$', instruction)
  17.     box_index = my_hash(label)
  18.     if op == '-':
  19.       boxes[box_index] = [(l, f) for l, f in boxes[box_index] if l != label]
  20.     else:
  21.       indices = [i for i, (l, f) in enumerate(boxes[box_index]) if l == label]
  22.       if indices:
  23.         boxes[box_index][indices[0]] = label, focal
  24.       else:
  25.         boxes[box_index].append((label, focal))
  26.  
  27.   return sum((b + 1) * (i + 1) * int(f) for b in range(256) for i, (l, f) in enumerate(boxes[b]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement