Skip to content

Commit c8ab67d

Browse files
committed
Implement 2024 day 13
1 parent 044c971 commit c8ab67d

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

2024/src/aoc/days/day13.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import re
2+
3+
import numpy
4+
5+
from . import CombinedRunner
6+
7+
NASTY_REGEX = r"""Button A: X\+(\d+), Y\+(\d+)
8+
Button B: X\+(\d+), Y\+(\d+)
9+
Prize: X=(\d+), Y=(\d+)"""
10+
11+
12+
class DayRunner(CombinedRunner):
13+
@classmethod
14+
def run_both(cls, input: str) -> tuple[int, int]:
15+
machines = re.findall(NASTY_REGEX, input)
16+
17+
cost_to_win = 0
18+
cost_to_win2 = 0
19+
scale = 10000000000000
20+
21+
for machine in machines:
22+
ax, ay, bx, by, px, py = map(int, machine)
23+
24+
X = numpy.array([[ax, bx], [ay, by]])
25+
B = numpy.array([px, py])
26+
B2 = numpy.array([px + scale, py + scale])
27+
28+
A = numpy.linalg.solve(X, B)
29+
A2 = numpy.linalg.solve(X, B2)
30+
31+
a_press, b_press = map(round, A)
32+
a_press2, b_press2 = map(round, A2)
33+
34+
if a_press * ax + b_press * bx == px and a_press * ay + b_press * by == py:
35+
cost_to_win += 3 * a_press + b_press
36+
37+
if (
38+
a_press2 * ax + b_press2 * bx == px + scale
39+
and a_press2 * ay + b_press2 * by == py + scale
40+
):
41+
cost_to_win2 += 3 * a_press2 + b_press2
42+
43+
return cost_to_win, cost_to_win2

2024/tests/samples/13.txt

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Button A: X+94, Y+34
2+
Button B: X+22, Y+67
3+
Prize: X=8400, Y=5400
4+
5+
Button A: X+26, Y+66
6+
Button B: X+67, Y+21
7+
Prize: X=12748, Y=12176
8+
9+
Button A: X+17, Y+86
10+
Button B: X+84, Y+37
11+
Prize: X=7870, Y=6450
12+
13+
Button A: X+69, Y+23
14+
Button B: X+27, Y+71
15+
Prize: X=18641, Y=10279

2024/tests/test_day13.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
from aoc.days.day13 import DayRunner
2+
3+
from . import get_data
4+
5+
6+
def test_sample_part1() -> None:
7+
assert DayRunner.part1(get_data(13)) == 480

0 commit comments

Comments
 (0)