Skip to content

Commit a110163

Browse files
committed
2024 day 13 part 1
1 parent 9fddf84 commit a110163

File tree

3 files changed

+83
-1
lines changed

3 files changed

+83
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
- 2021 - ★★★★★ ★★★★★ ★★★★★ ★★★
1616
- 2022 - ★★★★★ ★★★★★ ★★★★★ ★☆
1717
- 2023 - ★★★★★ ★★★★★ ★★★★★ ★★★☆
18-
- 2024 - ★★★★★ ★★★★★ ★★
18+
- 2024 - ★★★★★ ★★★★★ ★★
1919

2020
## How to use
2121

src/year2024/day13a.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""2024 - Day 13 Part 1: Claw Contraption"""
2+
3+
import re
4+
import sys
5+
from dataclasses import dataclass
6+
from typing import Self
7+
8+
type Point = tuple[int, int]
9+
10+
11+
@dataclass
12+
class Machine:
13+
a: Point
14+
b: Point
15+
prize: Point
16+
17+
@classmethod
18+
def from_text(cls, text: str) -> Self:
19+
first, second, third = text.split("\n")
20+
21+
ac, ar = re.findall(r"\d+", first)
22+
a = int(ar), int(ac)
23+
24+
bc, br = re.findall(r"\d+", second)
25+
b = int(br), int(bc)
26+
27+
pc, pr = re.findall(r"\d+", third)
28+
prize = int(pr), int(pc)
29+
30+
return cls(a, b, prize)
31+
32+
@property
33+
def min_tokens_win(self) -> int:
34+
min_cost = {(0, 0): 0}
35+
36+
ar, ac = self.a
37+
br, bc = self.b
38+
39+
for ai in range(100):
40+
for bi in range(1, 100):
41+
nr = ar * ai + br * bi
42+
nc = ac * ai + bc * bi
43+
44+
min_cost[(nr, nc)] = min(
45+
min_cost.get((nr - br, nc - bc), sys.maxsize) + 1,
46+
min_cost.get((nr - ar, nc - ac), sys.maxsize) + 3,
47+
)
48+
49+
return min_cost.get(self.prize, 0)
50+
51+
52+
def solve(task: str) -> int:
53+
machines = [Machine.from_text(block) for block in task.split("\n\n")]
54+
return sum(x.min_tokens_win for x in machines)

tests/src/year2024/test_day13a.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""2024 - Day 13 Part 1: Claw Contraption"""
2+
3+
from textwrap import dedent
4+
5+
from src.year2024.day13a import solve
6+
7+
8+
def test_solve():
9+
task = dedent(
10+
"""
11+
Button A: X+94, Y+34
12+
Button B: X+22, Y+67
13+
Prize: X=8400, Y=5400
14+
15+
Button A: X+26, Y+66
16+
Button B: X+67, Y+21
17+
Prize: X=12748, Y=12176
18+
19+
Button A: X+17, Y+86
20+
Button B: X+84, Y+37
21+
Prize: X=7870, Y=6450
22+
23+
Button A: X+69, Y+23
24+
Button B: X+27, Y+71
25+
Prize: X=18641, Y=10279
26+
"""
27+
).strip()
28+
assert solve(task) == 480

0 commit comments

Comments
 (0)