From c8ab67d1452d3762d2a542368c315f8841d18f34 Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Fri, 13 Dec 2024 08:36:20 +0100 Subject: [PATCH] Implement 2024 day 13 --- 2024/src/aoc/days/day13.py | 43 ++++++++++++++++++++++++++++++++++++++ 2024/tests/samples/13.txt | 15 +++++++++++++ 2024/tests/test_day13.py | 7 +++++++ 3 files changed, 65 insertions(+) create mode 100644 2024/src/aoc/days/day13.py create mode 100644 2024/tests/samples/13.txt create mode 100644 2024/tests/test_day13.py diff --git a/2024/src/aoc/days/day13.py b/2024/src/aoc/days/day13.py new file mode 100644 index 0000000..c959c1e --- /dev/null +++ b/2024/src/aoc/days/day13.py @@ -0,0 +1,43 @@ +import re + +import numpy + +from . import CombinedRunner + +NASTY_REGEX = r"""Button A: X\+(\d+), Y\+(\d+) +Button B: X\+(\d+), Y\+(\d+) +Prize: X=(\d+), Y=(\d+)""" + + +class DayRunner(CombinedRunner): + @classmethod + def run_both(cls, input: str) -> tuple[int, int]: + machines = re.findall(NASTY_REGEX, input) + + cost_to_win = 0 + cost_to_win2 = 0 + scale = 10000000000000 + + for machine in machines: + ax, ay, bx, by, px, py = map(int, machine) + + X = numpy.array([[ax, bx], [ay, by]]) + B = numpy.array([px, py]) + B2 = numpy.array([px + scale, py + scale]) + + A = numpy.linalg.solve(X, B) + A2 = numpy.linalg.solve(X, B2) + + a_press, b_press = map(round, A) + a_press2, b_press2 = map(round, A2) + + if a_press * ax + b_press * bx == px and a_press * ay + b_press * by == py: + cost_to_win += 3 * a_press + b_press + + if ( + a_press2 * ax + b_press2 * bx == px + scale + and a_press2 * ay + b_press2 * by == py + scale + ): + cost_to_win2 += 3 * a_press2 + b_press2 + + return cost_to_win, cost_to_win2 diff --git a/2024/tests/samples/13.txt b/2024/tests/samples/13.txt new file mode 100644 index 0000000..912f482 --- /dev/null +++ b/2024/tests/samples/13.txt @@ -0,0 +1,15 @@ +Button A: X+94, Y+34 +Button B: X+22, Y+67 +Prize: X=8400, Y=5400 + +Button A: X+26, Y+66 +Button B: X+67, Y+21 +Prize: X=12748, Y=12176 + +Button A: X+17, Y+86 +Button B: X+84, Y+37 +Prize: X=7870, Y=6450 + +Button A: X+69, Y+23 +Button B: X+27, Y+71 +Prize: X=18641, Y=10279 diff --git a/2024/tests/test_day13.py b/2024/tests/test_day13.py new file mode 100644 index 0000000..fd3e433 --- /dev/null +++ b/2024/tests/test_day13.py @@ -0,0 +1,7 @@ +from aoc.days.day13 import DayRunner + +from . import get_data + + +def test_sample_part1() -> None: + assert DayRunner.part1(get_data(13)) == 480