-
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
Showing
3 changed files
with
55 additions
and
1 deletion.
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
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,41 @@ | ||
"""2023 - Day 15 Part 2: Lens Library""" | ||
import re | ||
from collections import defaultdict | ||
from typing import TypeAlias | ||
|
||
from src.year2023.day15a import get_hash | ||
|
||
Boxes: TypeAlias = dict[int, dict[str, int]] | ||
|
||
|
||
def parse_task(task: str) -> Boxes: | ||
boxes: Boxes = defaultdict(dict) | ||
|
||
for step in task.split(","): | ||
[(label, op, focal)] = re.findall(r"([a-z]+)([=\-])(\d+)?", step) | ||
box = get_hash(label) | ||
|
||
if op == "=": | ||
boxes[box][label] = int(focal) | ||
elif op == "-": | ||
if label in boxes[box]: | ||
del boxes[box][label] | ||
else: | ||
raise ValueError(f"unknown op: {op}") | ||
|
||
return boxes | ||
|
||
|
||
def get_focus_power(boxes: Boxes) -> int: | ||
total = 0 | ||
|
||
for box in range(256): | ||
for slot, (_, focal) in enumerate(boxes[box].items(), start=1): | ||
total += (box + 1) * slot * focal | ||
|
||
return total | ||
|
||
|
||
def solve(task: str) -> int: | ||
boxes = parse_task(task) | ||
return get_focus_power(boxes) |
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,13 @@ | ||
"""2023 - Day 15 Part 2: Lens Library""" | ||
from textwrap import dedent | ||
|
||
from src.year2023.day15b import solve | ||
|
||
|
||
def test_solve(): | ||
task = dedent( | ||
""" | ||
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7 | ||
""" | ||
).strip() | ||
assert solve(task) == 145 |