advent-of-code/2024/13/two_reddit.py
2024-12-25 12:59:49 +01:00

65 lines
1.6 KiB
Python

#!/usr/bin/env python3
"""
Implementing:
https://www.reddit.com/r/adventofcode/comments/1hd7irq/2024_day_13_an_explanation_of_the_mathematics/
"""
import re
import sys
input_file = sys.argv[1]
with open(input_file) as fd:
lines = [line.rstrip() for line in fd.readlines()]
coords = tuple[int, int]
prizes: list[coords] = list()
buttons: list[tuple[coords, coords]] = list()
for li, line in enumerate(lines):
machine = li // 4
offset = li % 4
if offset == 0:
match = re.match(r"^Button A: X\+([0-9]+), Y\+([0-9]+)$", line)
assert match
button_a = int(match[1]), int(match[2])
elif offset == 1:
match = re.match(r"^Button B: X\+([0-9]+), Y\+([0-9]+)$", line)
assert match
button_b = int(match[1]), int(match[2])
buttons.append((button_a, button_b))
elif offset == 2:
match = re.match("^Prize: X=([0-9]+), Y=([0-9]+)$", line)
assert match
prize = int(match[1]), int(match[2])
# prize = prize[0] + 10000000000000, prize[1] + 10000000000000
prizes.append(prize)
assert len(prizes) == len(buttons)
ttoks = 0
token_a, token_b = 3, 1
for arcade, prize in enumerate(prizes):
butts = buttons[arcade]
button_a, button_b = butts
print(43, prize, button_a, button_b)
p_x, p_y = prize
a_x, a_y = button_a
b_x, b_y = button_b
denom = a_x * b_y - a_y * b_x
a = (p_x * b_y - p_y * b_x) / denom
b = (a_x * p_y - a_y * p_x) / denom
if not a.is_integer() or not b.is_integer():
print(76, None)
continue
toks = int(a) * token_a + int(b) * token_b
print(76, toks)
ttoks += toks
print(ttoks)