Advent of Code 2024 - Day 13Claw Contraption
| Problem statement | Source code | Tags: Mathematics
This problem pays tribute to 2020 day 24.
For each prize, we want to press button A times and button B times, such that , . We can rewrite this as a matrix equation:
I define a matrix type, based on rationals.
Then I parse my input into a (mat22 * (Q.t * Q.t)) list.
For each prize, I solve it by inverting the matrix:
If the inverse doesn't exist, then there are two possibilities: (1) the equations are inconsistent (e.g., nA + nB = 1 and 2nA + 2nB = 3); (2) the equations are degenerate (e.g., nA + nB = 1 and 2nA + 2nB = 2). Now theoretically for the second case, there still remains a relationship between and , which is (the other is equivalent to it), which should minimize the cost ; however, I found that actually this case never happens in the input, so I just ignore it.
Here's the function for inverting the matrix:
And here, for solving one equation:
The cost is straightforward to compute.
Part 2 just shifts all prizes by 10000000000000, but does not change the above logic at all. It was purely used to shoot down brute-force solutions.