The thirteenth day of Advent of Code was yesterday 12/13/2024!
If you’re here for the first time today, don’t forget to read the posts about
Day 1,
Day 2,
Day 3,
Day 4,
Day 5,
Day 6,
Day 7,
Day 8,
Day 9,
Day 10,
Day 11 and
Day 12.
I classified the thirteenth problem as medium (part 1) and medium (part 2).
Tips
- The program has a multi-line input
- You can use regular expressions to extract values from each line
- Each group of 4 lines brings 4 values, the input for the program
- You can view the problem as a system of linear equations
- The system has no solution when the equation system’s answer is not an integer
- Find the values of a and b that satisfy the equation. In this case, calculate the cost as
3*a + b
- If you use an optimizer like
scipy.optimize.linprog
or Pulp
you might have problems with the large numbers in part 2
- Model in Pulp:
def solve(ax, ay, bx, by, rx, ry):
model = LpProblem("Minimize Tokens", LpMinimize)
A = LpVariable("A", lowBound=0, cat=LpInteger)
B = LpVariable("B", lowBound=0, cat=LpInteger)
model += 3 * A + B
model += ax * A + bx * B == rx
model += ay * A + by * B == ry
model.solve()
return model, value(A), value(B)
from scipy.optimize import linprog
def minimize_cost(x, y, r, c, max_tokens=100):
A_eq = [x, y] # Coefficient matrix for equality constraints
b_eq = r # Right-hand side of the equations
result = linprog(
c,
A_eq=A_eq,
b_eq=b_eq,
method="highs",
bounds=[(0, max_tokens), (0, max_tokens)],
integrality=[1, 1],
)
# Check if the optimization was successful
if result.success:
a, b = result.x
print(
f"The optimized solution is: a = {a}, b = {b}, with a cost of {3*a + b} {result.fun}"
)
return a, b, 3 * a + b
else:
print("No valid solution (could not optimize).", result)
return None
How much Python do you need to know?
The chapters refer to my book Introduction to Programming with Python.