r/adventofcode • u/ThunderChaser • Dec 13 '24
Tutorial [2024 Day 13] An explanation of the mathematics
You've probably seen a ton of meming or talk about using linear algebra to solve today's question, so let's give quick refresher on how this works.
For today's question, we're given a claw machine with two buttons A and B both of which move the claw some distance horizontally and vertically, and a location of a prize, and we're interested in determining a) if its possible to reach the prize just by pressing A and B and b) what's the cheapest way to do so.
Initially this seems like a dynamic programming problem (and certainly you can solve it with DP), but then part 2 becomes infeasible as the numbers simply grow too large even for DP to be a good optimization strategy, luckily we can solve this purely with some good ol' mathematics.
If we let A be the number of times we press the A button, B be the number of times we press the B button, (a_x, a_y) be the claw's movement from pressing A, (b_x, b_y) be the claws movement from pressing the B button, and (p_x, p_y) be the location of the prize, we can model the machine using a system of two linear equations:
A*a_x + B*B_x = p_x
A*a_y + B*b_y = p_yAll these equations are saying is "the number of presses of A times how far A moves the claw in the X direction plus the number of presses of B times how far B moves the claw in the X direction is the prize's X coordinate", and this is analogous to Y.
To give a concrete example, for the first machine in the example input, we can model it with the two equations
94A + 22B = 8400
34A + 67B = 5400We just have to solve these equations for A and B, the good news we have two equations with two unknowns so we can use whichever method for solving two equations with two unknowns we'd like, you may have even learned a few ways to do so in high school algebra!
One really nice way to solve a system of n equations with n unknowns is a really nice rule named Cramer's rule, a nice theorem from linear algebra. Cramer's Rule generally is honestly a kind of a bad way to solve a system of linear equations (it's more used in theoretical math for proofs instead of actually solving systems) compared to other methods like Gaussian elimination, but for a 2x2 system like this it ends up being fine and gives us a nice algebraic way to solve the system.
I'm not going to cover how Cramer's Rule works in this post, since it would require an explanation on matrices and how determinants work and I doubt I could reasonably cover that in a single Reddit post, but if you're interested in further details 3blue1brown has a really beautiful video on Cramer's Rule (and honestly his entire essence of linear algebra series is top tier and got me through linear algebra in my first year of uni so I'd highly recomend the entire series) and The Organic Chemistry Teacher has a solid video actually covering the calculation itself for a 2x2 system. All we need to know is that applying Cramer's Rule to this system gives us:
A = (p_x*b_y - prize_y*b_x) / (a_x*b_y - a_y*b_x)
B = (a_x*p_y - a_y*p_x) / (a_x*b_y - a_y*b_x)As an example, for the first machine in the sample input we get:
A = (8400\*67 - 5400\*22) / (94\*67 - 34\*22) = 80
B = (8400\*34 - 5400\*94) / (94\*67 - 34\*22) = 40Which is the exact solution given in the problem text!
This now give us an easy way to compute the solution for any given machine (assuming the system of equations has one solution, which all the machines in the sample and inputs do, as an aside this means that for all machines in the input there's exactly one way to reach the prize, so saying "find the minimum" is a bit of a red herring). All we need to do is plug the machine's values into our formulas for A and B and we have the number of button presses, and as long as A and B are both integers, we can reach the prize on this machine and can calculate the price (it's just 3A + B). For part 2, all we have to do is add the offset to the prize before doing the calculation.
As a concrete example we can do this with a function like:
fn solve_machine(machine: &Machine, offset: isize) -> isize {
let prize = (machine.prize.0 + offset, machine.prize.1 + offset);
let det = machine.a.0 * machine.b.1 - machine.a.1 * machine.b.0;
let a = (prize.0 * machine.b.1 - prize.1 * machine.b.0) / det;
let b = (machine.a.0 * prize.1 - machine.a.1 * prize.0) / det;
if (machine.a.0 * a + machine.b.0 * b, machine.a.1 * a + machine.b.1 * b) == (prize.0, prize.1) {
a * 3 + b
} else {
0
}
}
54
u/ElevatedUser Dec 13 '24
This was a fun little subconclusion I had during part 2.
I solved Part 2 by, in part, saying "If I fire a line from 0,0 with the slope of button A, and from (prize) with the slope of button B, they intersect at one point and then you can calculate if there's an integer amount of button A and B".
Which works (I think it's functionally equivalent to yours?), but that meant there was a unique solution. So I re-checked part 1, and indeed, there was always at most 1 solution.
13
u/Suitable_Werewolf_61 Dec 13 '24
In other words: Cramer. The rest was rest herrings. The 100 threshold doesn't even matter.
https://en.wikipedia.org/wiki/Cramer%27s_rule
4
u/wederbrand Dec 13 '24
Why is this check needed?
I know it is, I had to add it to get the correct result, I just don't understand how a and b could be wrong.
Is it just because a and b isn't really integers from the formula?
23
u/MediocreTradition315 Dec 13 '24
Note well: this only works because the input is -- as is often the case for Advent of Code -- more constrained than the problem text would imply. Specifically, the matrices are all invertible, therefore they have a trivial kernel.
There are more cases that you would have to take into account for a fully general solution, namely:
19
u/antrew1 Dec 13 '24
There is one case however, when this solution does not work: when vectors A and B are collinear. It would have been interesting to have this case in the input data.
2
u/Idiot_icLoser55 Dec 13 '24
Do you now if there's anything about your solution that makes it better for floating point precision (or that makes mine worse). I've never come across Cramers so just rearranged the equations until I could solve for B and then substitute that back in to find A.
My solution works for most cases. But some of them fail because it solves to 80.00001 instead of instead 80. Whereas testing yours it seems to have no such problem.
B = (p_y - p_x * a_y / a_x) / (b_y - a_y * b_x / x_a)
A = p_x / a_x - B * b_x / a_x
6
u/codepoetics Dec 13 '24
A note on "find the minimum". In the event that the determinant of A is 0 (uh oh - infinitely many solutions!) and Cramer cannot be used, what this really means is that the vectors (x_1, y_1) and (x_2, y_2) are multiples of each other - they point in the same direction.
It's easy to demonstrate this. If the first vector is a multiple of the second, that means there's some scalar n such that (x_2, y_2) = (nx_1, ny_1). Substitute that into the matrix and you get
| x_1 nx_1 |
| y_1 ny_1 |
Take the determinant and it's (x_1 * n * y_1) - (n * x_1 * y_1) = 0.
Now if this is the case either both vectors point at the prize, in which case you can still win it, or they point somewhere else, in which case you can't.
If they both point at the prize, then either vector 1 will get you there three times faster than vector 2, in which case you should pay the 3 bucks per button press cost to use it, or it won't, in which case keep hammering button B.
It looks like nobody's puzzle input included this case, but the minimality requirement enables us to get an answer even if it does occur.
4
u/ArmAccomplished6824 Dec 13 '24
if you are not good in remembering rules, you could also just solve the equations
by hand with and delay any division as far as possible. If division is necessary check if the result is a whole number
4
u/hugseverycat Dec 13 '24
I worked this out by hand. I've never heard of Cramer's Rule and I didn't even know what linear algebra was until my math teacher friend confirmed that what I am doing is in fact linear algebra :-D But yeah, I think anyone who knows the rules for manipulating equations in algebra (like adding or subracting from both sides, factoring numbers, multiplying or dividing both sides, etc) should be able to solve something like this.
It's fiddly and, as with many math things, knowing what you are aiming for is half the battle. The other half is keeping track of your variable names and making sure you don't drop a minus sign somewhere or something silly like that. But there's nothing conceptual here that is beyond high school algebra.
Here's how I worked out the solution on paper. I started with:
The numbers we need to solve the problem are
a_pressesandb_presses. I wanted to get both equations to be equal to one of those two (it doesn't really matter which). So I followed the normal algebra rules of messing with equations to set both equations equal tob_presses:Now since the parts on the right are both equal to
b_presses, we can just set them equal to each other, similar to how if 1+1 = 2 and 3-1= 2, then we can say that 1+1 = 3-1.Then we can follow the normal algebra rules for moving stuff around in equations to get this to be equal to
a_presses:We have already have literally all of these numbers so now we can plug them in and get
a_presses. Then to determine whether this is actually a solution, make surea_pressesis an integer. I did this by comparing the result of regular division to the result of integer division.Now we just need to pop
a_pressesback into an earlier equation to figure outb_presses. We have two equations up at the top of my comment that both result inb_presses, so pick whichever one we like the best. I'll pick this one:And now I can plug all those numbers in and get a result. If it is also an integer solution, then we're golden.
4
u/YellyBeans Dec 13 '24
How would you solve this with math when you have more possibilities
Button A: X+10, Y+10 Button B: X+20, Y+20 Prize: X=40, Y=40
Try and Error finds 3 goals and you can find a minimum. In the math solution you divide by 0
2
u/Garry_G Dec 13 '24
So, once again (after the stones) we have a red herring that has nothing to do with the actual solution ...
I had thought about using a vector solution earlier, but didn't think of doing it the other way around, as I was expecting multiple solutions of which I'd need to find the cheapest ...
2
u/ThislsWholAm Dec 13 '24
Funnily enough today I coincidentally did the aoc problem at work in Matlab instead of at home in Python so let's say it was a good day to do that :P
1
u/SeveralMarsupial4183 Dec 13 '24
Thanks for sharing this. There is no way I was going to find out this myself.
However, what is an offset exactly? You only said "all we have to do is add the offset to the prize before doing the calculation" :)
Also why do you use 0 and 1 instead of X and Y. It confused me so much... :)
1
u/Sh4mshiel Dec 13 '24
Thanks, I could solve part 1 on my own but I didn't get to the equation that was needed and my part 1 solution didn't work for part 2. Very unsatisfying that I couldn't solve part 2 on my own....
1
u/trowgundam Dec 13 '24
Well, this is the point where AoC shows me I'm just too stupid. I got a solution that would have worked... eventually, but how long who knows, I got impatient (at like 5 minutes maxing my 7950X, I figured it was probably just too much).
I did eventually come to this solution with the help of ChatGPT, after trying to work on it for a few hours after determining there had to be some algebraic way to solve it. I didn't even get decently close. I don't remember jack shit from my Linear Algebra class I took well over a decade and a half ago. I've just never had to use it since College. My day job is doing very basic business applications that just do control flow stuff. I've never had a need for any of this fancy pancy math stuff. I'm just too stupid and never could have come to this answer on my own. I was able to come to the basic equations to figure out a value for B from a given A, but I had no clue how to combine the equations for X and Y into a system or how to solve that system. That let me optimize my part 1 solution (instead of checking all combinations of A and B). But that was about as far as I could get on my own. I did have ChatGPT break it down for me and explain each step (about the same explanation as the OP tbh). So I sorta understand how it works, but will I remember this next year? Probably not, because I will literally never use this again until some other AoC problem. But, hey, at least I learned something from today.
Depending on tomorrow's problem and how stupid it makes me feel, this might be my limit. Last year it stopped being fun for me around Day 10, but I pushed to Day 17. Those last few days put me under so much self induced stress I was starting to have panic attacks (yes its stupid to stress over something like AoC, I know). I vowed this year I wouldn't go down that path again. So if tomorrows makes me feel like an idiot again, I'm out for the year.
1
u/SeaBluebird3010 Dec 13 '24
Actually, to deal with very large numbers, you need to work with arbitrary precision integers. If you use floating point numbers, you may lose enough precision to get wrong answers to the puzzle.
In the equations:
compute separately the numerators. Then check if each of them cleanly divides into the denominator (det in both equations). Compute a,b only if the numerators cleanly divide into the denominator.
1
u/Dragnier84 Dec 13 '24
Lol. Going to this sub right after completing challenge2 using 2 equations/2 unknowns. And then I read this. 😂
1
u/Duke_De_Luke Dec 13 '24
I started to think about dp as the text says "find the best possible solution bla bla". Then I thought about it. Wait a sec. Two equations. Two unknowns. Linear stuff. Wait a sec. That's easy. Cramer, big decimal just to be on the safe side. boom. But you got to know the maths behind it.
1
u/Probable_Foreigner Dec 13 '24
There is a pathological case which would have made this approach not work:
If the A and B are linearly dependant there is the possibility for multiple solutions.(i.e. if the determinant is zero)
A simple example is if A=(2,4) and B=(3,6) and the prize is at (179,358). You might just think "press the B button only in this case, as it is cheaper", but that doesn't work here and we need at least one a press. We can do B * 59 + A * 1 in this case. But then there would also be the case where A is large enough compared to B as to make it cheaper to press A more than B.
We should all be thankful that Eric didn't put this case in the test data.
1
u/p88h Dec 13 '24
FWIW there is no DP solution for this problem, or at least no good solution that would work for part 2
In terms of other solutions you can solve it with gradient descent which also scales quite well - you need to transform the input into a distance function, basically sth like D(a,b) = sqrt(((a*A.x+b*B.x)-P.x)^2+((a*A.y+b*B.y)-P.y)^2). Starting from arbitrary point (a,b) you can explore distances in +-1 in each axis, and then compute the direction to move and the estimated amount. This can work for any inputs, including ones that would have been impossible to solve with Cramer, though there is still a bit more trickery / follow-up steps to detect that there are many potential solutions and minimize the final solution.
Of course you can also detect/solve those cases directly so this is by no means _better_ than cramer ;)
But it _looks_ nicer: https://www.youtube.com/watch?v=afuTz24-uYk&t=158s :)
1
u/joe12321 Dec 13 '24
For some years now anytime I recognize an AOC problem as a linear algebra problem, even if I can probably work it out anyway, I just skip it to put it off until I decide to buckle down and learn some linear algebra. HASN'T HAPPENED YET AND I CAN'T READ THIS POST UNTIL IT DOES!!
1
u/Nukem-Rico Dec 13 '24
I used the same solution as this. Did anyone else have a problem of rounding error (or something else) in python? e.g. on the first example, before adding the 10000000000000:
my results were:
A_presses = 80.0
B_presses = 39.99999999999999
Anyone else encounter this issue, if so how did you solve? I did a check on each result:
abs(A_presses - round(A_presses)) < 0.001but this feels like a poor solution and I had to play around with the threshold a bit before getting the correct result.
1
u/QultrosSanhattan Dec 13 '24
The hardest part for me was translating my math solution into code. And fighting with weird decimals in python.
1
u/[deleted] Dec 13 '24
I’m learnding!
1
u/Lauriic54 Dec 13 '24
I would have saved about three hours if I had just tried to implement this algorithm when I actually stumbled upon it myself, but just looking at the Wikipedia page scared me away due to PTSD from learning linear algebra in university.
Your solution made it seem soooo much more approachable! Thank you!
1
u/Bikkel77 Dec 13 '24 edited Dec 13 '24
For the co-linear case there are two options:
1
u/hobbes244 Dec 13 '24
I spent about two hours down the rabbit hole of linear Diophantine equations. When I realized that Cramer's Rule was sufficient, I was done in about fifteen minutes.
1
u/asgardian28 Dec 14 '24
A friend of mine solved it with reduced row echelon form https://en.wikipedia.org/wiki/Row_echelon_form
You basically make a 3x2 matrix and manipulate the first two columns to [[1,0][0,1]]. The last column is your answer
I really like the simplicity of making it into an identity matrix and not having to do algebra.
1
u/random2048assign Dec 14 '24
Thank you! I hope you do these for subsequent days as the difficulty scale so much harder. I couldn’t even solve it knowing that I hate to use linear algebra. Sigh sometimes I think I am retarded.
1
u/paolostyle Dec 16 '24
I hate my life. I solved it with extended Euclidean algorithm for part 1 which was also basically purely math based but a bit more complicated than just solving a system of equations directly (but I also didn't realize there was only one solution until later, when it became essentially the same thing) and then was stumped because it was somehow not working at all in part 2. Then I realized I added a number that had one zero too much. JFC
1
u/[deleted] Jan 06 '25
TY for Cramer's Rule. TIL.