-
Notifications
You must be signed in to change notification settings - Fork 0
/
day-15.py
64 lines (48 loc) · 1.6 KB
/
day-15.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
file = open("day-15.txt", "r")
text = file.read()
steps = text.split(",")
#################### Part 1 ####################
def hash(s: str):
result = 0
for char in s:
result += ord(char)
result *= 17
result %= 256
return result
def initialize(steps: list[str]):
total = 0
for step in steps:
total += hash(step)
return total
print("Solution 1: ", initialize(steps))
#################### Part 2 ####################
def focusing_power(steps: list[str]):
# build hashmap
hashmap = {k: [] for k in range(256)}
for step in steps:
if "-" in step:
label = step.split("-")[0]
box = hash(label)
labels = [lens[0] for lens in hashmap[box]]
if any(label == l for l in labels):
label_index = labels.index(label)
del hashmap[box][label_index]
else:
# '=' operation
operation = step.split("=")
label = operation[0]
focal_length = operation[1]
box = hash(label)
labels = [lens[0] for lens in hashmap[box]]
if any(label == l for l in labels):
label_index = labels.index(label)
hashmap[box][label_index][1] = int(focal_length)
else:
hashmap[box].append([label, int(focal_length)])
# calculate focusing power
focusing_power = 0
for i in range(256):
for j, lens in enumerate(hashmap[i]):
focusing_power += (i + 1) * (j + 1) * lens[1]
return focusing_power
print("Solution 2: ", focusing_power(steps))