-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday15.py
More file actions
40 lines (31 loc) · 956 Bytes
/
day15.py
File metadata and controls
40 lines (31 loc) · 956 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def hash_step(step):
hash = 0
for c in step:
hash += ord(c)
hash *= 17
hash %= 256
return hash
def part1(input):
return sum(hash_step(step) for step in input.split(","))
def part2(input):
boxes = [[] for _ in range(256)]
for step in input.split(","):
if "-" in step:
label = step[:-1]
hash = hash_step(label)
boxes[hash] = list(filter(lambda box: box[0] != label, boxes[hash]))
else:
label = step[:-2]
focal = int(step[-1])
hash = hash_step(label)
for lens in boxes[hash]:
if lens[0] == label:
lens[1] = focal
break
else:
boxes[hash].append([label, focal])
answer = 0
for i, box in enumerate(boxes):
for j, lens in enumerate(box):
answer += (i + 1) * (j + 1) * lens[1]
return answer