|
| 1 | +import numpy as np |
| 2 | +from scipy.optimize import linprog |
| 3 | + |
| 4 | + |
| 5 | +with open("input") as f: |
| 6 | + ls = f.read().strip().split("\n") |
| 7 | + |
| 8 | +tasks = [] |
| 9 | +for l in ls: |
| 10 | + toggles, *buttons, counters = l.split() |
| 11 | + toggles = [x == "#" for x in toggles[1:-1]] |
| 12 | + moves = [set(map(int, b[1:-1].split(","))) for b in buttons] |
| 13 | + counters = list(map(int, counters[1:-1].split(","))) |
| 14 | + tasks.append((toggles, moves, counters)) |
| 15 | + |
| 16 | + |
| 17 | +def solve(goal, moves, part1): |
| 18 | + n, m = len(moves), len(goal) |
| 19 | + c = [1] * n |
| 20 | + A_eq = [[i in move for move in moves] for i in range(m)] |
| 21 | + bounds = [(0, None)] * n |
| 22 | + if part1: |
| 23 | + c += [0] * m |
| 24 | + A_eq = np.hstack([A_eq, -2 * np.eye(m)]) |
| 25 | + bounds += [(None, None)] * m |
| 26 | + return linprog(c, A_eq=A_eq, b_eq=goal, bounds=bounds, integrality=True).fun |
| 27 | + |
| 28 | + |
| 29 | +# Part 1 |
| 30 | +print(sum(solve(goal, moves, True) for goal, moves, _ in tasks)) |
| 31 | + |
| 32 | +# Part 2 |
| 33 | +print(sum(solve(goal, moves, False) for _, moves, goal in tasks)) |
0 commit comments