My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add solution for 2023/15

+46
+46
2023/day15.py
··· 1 + import fileinput 2 + from collections import defaultdict 3 + 4 + 5 + def HASH(code): 6 + val = 0 7 + for c in code: 8 + val += ord(c) 9 + val *= 17 10 + val %= 256 11 + return val 12 + 13 + 14 + # Parse problem input. 15 + STEPS = next(fileinput.input()).strip().split(',') 16 + 17 + # Solve part 1. 18 + print("Part 1:", sum(HASH(step) for step in STEPS)) 19 + 20 + # Solve part 2. 21 + BOXES = defaultdict(list) 22 + 23 + for step in STEPS: 24 + if step[-1] == '-': 25 + label = step[:-1] 26 + box = HASH(label) 27 + BOXES[box] = [lens for lens in BOXES[box] if lens[0] != label] 28 + 29 + else: 30 + focal = int(step[-1]) 31 + label = step[:-2] 32 + box = HASH(label) 33 + 34 + for i, (other_label, other_focal) in enumerate(BOXES[box]): 35 + if other_label == label: 36 + BOXES[box][i] = (label, focal) 37 + break 38 + else: 39 + BOXES[box].append((label, focal)) 40 + 41 + lenses = {} 42 + for box_num, box in BOXES.items(): 43 + for slot_num, (label, focal) in enumerate(box, start=1): 44 + lenses[label] = (box_num + 1) * slot_num * focal 45 + 46 + print("Part 2:", sum(lenses.values()))