-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Ted Cassirer
committed
Jan 5, 2024
1 parent
854c596
commit 3b62132
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |