Day 15 - Advent of Code 2023
Working solutions for the day 15 puzzles.
Part One
""" day_15_01.py """
# usage: python3 day_15_01.py < input
def digest(text):
""" hash per puzzle description """
value = 0
for t in text:
value = ((value + ord(t)) * 17) % 256
return value
answer = 0
for item in input().split(','):
answer += digest(item)
print(answer)
Part Two
""" day_15_02.py """
# usage: python3 day_15_02.py < input
def digest(text):
""" hash per puzzle description """
value = 0
for t in text:
value = ((value + ord(t)) * 17) % 256
return value
boxes = [[] for _ in range(256)]
for item in input().split(','):
if item.endswith('-'):
label = item[:-1]
box = digest(label)
boxes[box] = [(i, j) for i, j in boxes[box] if i != label]
else:
label, focal_length = item.split('=')
box = digest(label)
try:
j = [i for i, _ in boxes[box]].index(label)
boxes[box][j] = (label, focal_length)
except ValueError:
boxes[box].append((label, focal_length))
answer = 0
for i, box in enumerate(boxes):
for j, (_, focal_length) in enumerate(box):
answer += (i + 1) * (j + 1) * int(focal_length)
print(answer)