Spaces:
Running
Running
File size: 1,383 Bytes
a4da721 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import re
file = "input.txt"
def solve():
with open(file, 'r') as f:
machines = []
for line in f:
match = re.match(r"Button A: X\+(\d+), Y\+(\d+)\nButton B: X\+(\d+), Y\+(\d+)\nPrize: X=(\d+), Y=(\d+)", line.strip())
if match:
ax, ay, bx, by, px, py = map(int, match.groups())
machines.append(((ax, ay), (bx, by), (px, py)))
def get_min_cost(machines):
min_costs = []
for (ax, ay), (bx, by), (px, py) in machines:
min_cost = float('inf')
for a in range(101):
for b in range(101):
if a * ax + b * bx == px and a * ay + b * by == py:
min_cost = min(min_cost, 3 * a + b)
min_costs.append(min_cost)
return min_costs
min_costs = get_min_cost(machines)
total_cost = sum(cost for cost in min_costs if cost != float('inf'))
num_prizes = sum(1 for cost in min_costs if cost != float('inf'))
print(total_cost)
offset = 10000000000000
machines_part2 = []
for (ax, ay), (bx, by), (px, py) in machines:
machines_part2.append(((ax, ay), (bx, by), (px + offset, py + offset)))
min_costs_part2 = get_min_cost(machines_part2)
total_cost_part2 = sum(cost for cost in min_costs_part2 if cost != float('inf'))
print(total_cost_part2)
solve() |