2023/day15.py

55 lines
1.2 KiB
Python
Raw Normal View History

2023-12-29 21:03:50 +00:00
import os
import sys
from collections import defaultdict
2024-01-04 03:43:34 +00:00
def hash(s: str) -> int:
2023-12-29 21:03:50 +00:00
v = 0
for c in s:
if c == ",":
continue
v += ord(c)
v *= 17
v %= 256
return v
2024-01-04 03:43:34 +00:00
def main() -> None:
with open(sys.argv[1]) as f:
s = f.read().strip()
boxes: defaultdict[int, list[tuple[str, int]]] = defaultdict(list)
part1 = 0
for s_ in s.split(","):
part1 += hash(s_)
if s_[-1] == "-":
label = s_[:-1]
h = hash(label)
for i in range(len(boxes[h])):
if boxes[h][i][0] == label:
del boxes[h][i]
break
elif s_[-2] == "=":
label = s_[:-2]
focal = int(s_[-1])
h = hash(label)
for i in range(len(boxes[h])):
if boxes[h][i][0] == label:
boxes[h][i] = (label, focal)
break
else:
boxes[h].append((label, focal))
part2 = 0
for (box_i, box) in boxes.items():
for (slot, (_, focal)) in enumerate(box):
part2 += (box_i + 1) * (slot + 1) * focal
print(part1, part2)
if __name__ == "__main__":
main()