Spaces:
Running
Running
| 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() |