48 lines
1.5 KiB
Python
48 lines
1.5 KiB
Python
def test(input, solution):
|
|
print(f"Running input {input}")
|
|
result = process(input)
|
|
print(f"Solution was {result}")
|
|
assert result == solution
|
|
|
|
def run():
|
|
file = open("input.txt", "r")
|
|
return process(file.read()[:-1])
|
|
|
|
def hash_value(word):
|
|
count = 0
|
|
for character in word:
|
|
count += ord(character)
|
|
count *= 17
|
|
count = count % 256
|
|
return count
|
|
|
|
def process(input):
|
|
labels = []
|
|
focal_lengths = []
|
|
for _ in range(256):
|
|
labels.append([])
|
|
focal_lengths.append([])
|
|
words = input.split(",")
|
|
for word in words:
|
|
if word[-1] == "-":
|
|
label = word[:-1]
|
|
index = hash_value(label)
|
|
if label in labels[index]:
|
|
inner_index = labels[index].index(label)
|
|
labels[index].pop(inner_index)
|
|
focal_lengths[index].pop(inner_index)
|
|
else:
|
|
[label, focal_length] = word.split("=")
|
|
index = hash_value(label)
|
|
if label in labels[index]:
|
|
inner_index = labels[index].index(label)
|
|
focal_lengths[index][inner_index] = focal_length
|
|
else:
|
|
labels[index].append(label)
|
|
focal_lengths[index].append(focal_length)
|
|
total = 0
|
|
for (box_number, (label_list, focal_length_list)) in enumerate(zip(labels, focal_lengths)):
|
|
for (lens_number, (label, focal_length)) in enumerate(zip(label_list, focal_length_list)):
|
|
total += (box_number + 1) * (lens_number + 1) * int(focal_length)
|
|
return total
|