diff --git a/aoc_cas/aoc2023/day15.py b/aoc_cas/aoc2023/day15.py new file mode 100644 index 0000000..a4ac1f4 --- /dev/null +++ b/aoc_cas/aoc2023/day15.py @@ -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) diff --git a/tests/fixtures/2023/15.txt b/tests/fixtures/2023/15.txt new file mode 100644 index 0000000..2a94874 --- /dev/null +++ b/tests/fixtures/2023/15.txt @@ -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 \ No newline at end of file