Skip to content

Commit

Permalink
2023 day 15 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Jan 7, 2024
1 parent b0a706b commit 6145f6b
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
- 2020 - ★★★★★ ★★★★★ ★★★★★ ☆
- 2021 - ★★★★★ ★★★★★ ★★★★★ ★★★
- 2022 - ★★★★★ ★★★★★ ★★★★★ ★☆
- 2023 - ★★★★☆ ★☆★★☆ ★★☆★
- 2023 - ★★★★☆ ★☆★★☆ ★★☆★

## How to use

Expand Down
41 changes: 41 additions & 0 deletions src/year2023/day15b.py
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)
13 changes: 13 additions & 0 deletions tests/src/year2023/test_day15b.py
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

0 comments on commit 6145f6b

Please sign in to comment.