aoc2023/d15/run.py

31 lines
569 B
Python
Raw Normal View History

2023-12-15 16:24:51 +00:00
import sys
def hash(l):
c = 0
for w in l:
c += ord(w)
c *= 17
c = c % 256
return c
2023-12-15 23:26:27 +00:00
L = sys.stdin.read().split(',')
print(sum(hash(l) for l in L))
2023-12-15 16:24:51 +00:00
B = [ dict() for _ in range(256) ]
2023-12-15 23:26:27 +00:00
for l in L:
2023-12-15 16:24:51 +00:00
e = l.find('=')
d = l.find('-')
i = max(e,d)
lbl = l[:i]
box = hash(lbl)
if e > 0: # set
v = int(l[i+1:])
B[box][lbl] = v
elif d > 0: # remove
if lbl in B[box]:
del B[box][lbl]
print(sum((i+1)*(j+1)*v for i, b in enumerate(B) for j,(k,v) in enumerate(b.items())))