Skip to content

Commit

Permalink
Day 15
Browse files Browse the repository at this point in the history
  • Loading branch information
Ted Cassirer committed Jan 5, 2024
1 parent 854c596 commit 3b62132
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
49 changes: 49 additions & 0 deletions aoc_cas/aoc2023/day15.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from typing import Iterator


def parse_sequence(data: str) -> Iterator[str]:
for sequence in data.split(","):
yield sequence


def hash(string: str) -> int:
val = 0
for c in string:
val += ord(c)
val *= 17
val %= 256
return val


def part_a(data: str) -> int:
return sum(hash(seq) for seq in parse_sequence(data))


def part_b(data: str) -> int:
boxes = [dict() for _ in range(256)]

for i, seq in enumerate(parse_sequence(data)):
if "=" in seq:
label, focal_length = seq.split("=")
box = boxes[hash(label)]
if label in box:
box[label][1] = int(focal_length)
else:
box[label] = [i, int(focal_length)]
else:
label = seq[:-1]
box = boxes[hash(label)]
box.pop(label, None)

focusing_power = 0
for box_num, box in enumerate(boxes, start=1):
lenses = sorted(box.values())
for lens_num, (_, focal_length) in enumerate(lenses, start=1):
focusing_power += box_num * lens_num * focal_length
return focusing_power


if __name__ == "__main__":
from aoc_cas.util import solve_with_examples

solve_with_examples(year=2023, day=15)
3 changes: 3 additions & 0 deletions tests/fixtures/2023/15.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7
1320
145

0 comments on commit 3b62132

Please sign in to comment.