|
| 1 | +import re |
| 2 | +from sympy import symbols, Eq, solve |
| 3 | + |
| 4 | +A_PRICE = 3 |
| 5 | +B_PRICE = 1 |
| 6 | + |
| 7 | + |
| 8 | +def load_data(filename): |
| 9 | + with open(filename, "r") as f: |
| 10 | + data = f.read().split("\n\n") |
| 11 | + |
| 12 | + machines = [] |
| 13 | + for machine in data: |
| 14 | + machine = re.findall(r"\d+", machine) |
| 15 | + machine = list(map(int, machine)) |
| 16 | + machines.append(machine) |
| 17 | + |
| 18 | + return machines |
| 19 | + |
| 20 | + |
| 21 | +def find_way_to_win(machine): |
| 22 | + a1, a2, b1, b2, r1, r2 = machine |
| 23 | + r1 = r1 + 10000000000000 # fix for unit conversion |
| 24 | + r2 = r2 + 10000000000000 # fix for unit conversion |
| 25 | + |
| 26 | + x, y = symbols("x,y") |
| 27 | + eq1 = Eq((a1 * x + b1 * y), r1) |
| 28 | + eq2 = Eq((a2 * x + b2 * y), r2) |
| 29 | + |
| 30 | + sol_dict = solve((eq1, eq2), (x, y)) |
| 31 | + x = sol_dict[x] |
| 32 | + y = sol_dict[y] |
| 33 | + |
| 34 | + if x == int(x) and y == int(y): |
| 35 | + return x, y |
| 36 | + else: |
| 37 | + return 0, 0 |
| 38 | + |
| 39 | + |
| 40 | +def calculate_tokens(machines): |
| 41 | + token = 0 |
| 42 | + for machine in machines: |
| 43 | + a, b = find_way_to_win(machine) |
| 44 | + token += a * A_PRICE + b * B_PRICE |
| 45 | + return token |
| 46 | + |
| 47 | + |
| 48 | +if "__main__" == __name__: |
| 49 | + machines = load_data("Day_13/puzzle_input.txt") |
| 50 | + print(calculate_tokens(machines)) |
0 commit comments