Day 13 - Advent of Code 2024
13 December 2024
Working solutions for the day 13 puzzles.
Part One
""" day_13_01.py """
# usage: python3 day_13_01.py < input
import re
import sys
def cost(claw):
""" solve per puzzle description """
costs = [3 * a + b for a in range(100) for b in range(100)
if (a * int(claw[0][0]) + b * int(claw[1][0]),
a * int(claw[0][1]) + b * int(claw[1][1])) ==
(int(claw[2][0]), int(claw[2][1]))]
return min(costs) if costs else 0
total = 0
with sys.stdin as infile:
machines_left = True
while machines_left:
machine = [re.findall(r'\d+', infile.readline()) for _ in range(3)]
total += cost(machine)
machines_left = infile.readline() != ''
print(total)
Part Two
""" day_13_02.py """
# usage: python3 day_13_02.py < input
import re
import sys
def cost(claw):
""" two equations in two variables """
xa, ya = claw[0][0], claw[0][1]
xb, yb = claw[1][0], claw[1][1]
x, y = claw[2][0] + 10000000000000, claw[2][1] + 10000000000000
b = (x / xa - y / ya) / (xb / xa - yb / ya)
if abs(b - round(b)) > 0.0001:
return 0
a = (x - b * xb) / xa
return 3 * round(a) + round(b)
total = 0
with sys.stdin as infile:
machines_left = True
while machines_left:
machine = [(int(x), int(y)) for x, y in
[re.findall(r'\d+', infile.readline()) for _ in range(3)]]
total += cost(machine)
machines_left = infile.readline() != ''
print(total)