Skip to content

Commit

Permalink
day 15
Browse files Browse the repository at this point in the history
  • Loading branch information
nrlulz committed Dec 15, 2023
1 parent d1f842f commit e8ccd15
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
71 changes: 71 additions & 0 deletions aoc2023/day15.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import pathlib
from collections import defaultdict

base_dir = pathlib.Path(__file__).parent
filename = base_dir / "day15_input.txt"

with open(base_dir / filename) as f:
lines: list[str] = f.read().strip().split(",")

Lens = tuple[str, int]


def the_hash_algorithm(input: str) -> int:
value = 0
for char in input:
value += ord(char)
value *= 17
value %= 256
return value


def find_lens_index_by_label(lenses: list[Lens], label: str) -> int:
for i, lens in enumerate(lenses):
if lens[0] == label:
return i
return -1


def part_1():
return sum(the_hash_algorithm(line) for line in lines)


def part_2():
boxes: defaultdict[int, list[Lens]] = defaultdict(list)

for line in lines:
if line.endswith("-"):
label = line[:-1]
box_number = the_hash_algorithm(label)
box_lenses = boxes[box_number]

lens_index = find_lens_index_by_label(box_lenses, label)
if lens_index != -1:
box_lenses.pop(lens_index)
else:
label, focal_length = line.split("=")
focal_length = int(focal_length)
lens = label, focal_length
box_number = the_hash_algorithm(label)
box_lenses = boxes[box_number]

existing_lens_index = find_lens_index_by_label(box_lenses, label)

if existing_lens_index == -1:
box_lenses.append(lens)
else:
box_lenses[existing_lens_index] = lens

focal_power = 0

for box_number, box_lenses in boxes.items():
for i, lens in enumerate(box_lenses, start=1):
_, focal_length = lens
focal_power += (box_number + 1) * focal_length * i

return focal_power


print(f"{the_hash_algorithm('HASH')=}")
print(f"answer_p1 = {part_1()}")
print(f"answer_p1 = {part_2()}")
1 change: 1 addition & 0 deletions aoc2023/day15_test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7

0 comments on commit e8ccd15

Please sign in to comment.