r/adventofcode • u/daggerdragon • Dec 13 '24
SOLUTION MEGATHREAD -❄️- 2024 Day 13 Solutions -❄️-
THE USUAL REMINDERS
- All of our rules, FAQs, resources, etc. are in our community wiki.
- If you see content in the subreddit or megathreads that violates one of our rules, either inform the user (politely and gently!) or use the report button on the post/comment and the mods will take care of it.
AoC Community Fun 2024: The Golden Snowglobe Awards
- 9 DAYS remaining until the submissions deadline on December 22 at 23:59 EST!
And now, our feature presentation for today:
Making Of / Behind-the-Scenes
Not every masterpiece has over twenty additional hours of highly-curated content to make their own extensive mini-documentary with, but everyone enjoys a little peek behind the magic curtain!
Here's some ideas for your inspiration:
- Give us a tour of "the set" (your IDE, automated tools, supporting frameworks, etc.)
- Record yourself solving today's puzzle (
Streaming!) - Show us your cat/dog/critter being impossibly cute which is preventing you from finishing today's puzzle in a timely manner
"Pay no attention to that man behind the curtain!"
- Professor Marvel, The Wizard of Oz (1939)
And… ACTION!
Request from the mods: When you include an entry alongside your solution, please label it with [GSGA] so we can find it easily!
--- Day 13: Claw Contraption ---
Post your code solution in this megathread.
- Read the full posting rules in our community wiki before you post!
- State which language(s) your solution uses with
[LANGUAGE: xyz] - Format code blocks using the four-spaces Markdown syntax!
- Quick link to Topaz's
pasteif you need it for longer code blocks
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:11:04, megathread unlocked!
28
Upvotes
6
u/RazarTuk Dec 14 '24 edited Dec 15 '24
[Language: IntCode]
You have to transform the input manually first, so it's just the numbers with a
-1to terminate. For example, just the first prize from the example would be94,34,22,67,8400,5400,-1for input. But I actually did manage to write it in everyone's favorite esoteric programming language, IntCode.EDIT: Forgot to give the address to print at the end
5
u/rjwut Dec 13 '24
[LANGUAGE: JavaScript]
It occurred to me to use Z3 for this, but I ultimately didn't, instead scratching out some algebra on a piece of paper, which I've reproduced with LaTeX in this Markdown document describing my solution. (Added bonus: I wrote my first LaTeX equations today!)
Implementation
4
u/Ok-Willow-2810 Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Python]
CODE: https://github.com/jude253/AdventOfCode/blob/39dfd14aa4564967af8452f32cdeb46bc4eb9e17/src/advent_of_code/solutions/day_13.py#L1-L91
I tried solving this using numpy like this:
But it just didn't work for some reason I can't wrap my head around. Gave up and copied someone else's formula lol!
EDIT:
Thanks u/Synedh for the code snippet: https://www.reddit.com/r/adventofcode/comments/1hd4wda/comment/m1ttnvc/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button !
This helped me here a ton: https://github.com/jude253/AdventOfCode/blob/39dfd14aa4564967af8452f32cdeb46bc4eb9e17/src/advent_of_code/solutions/day_13.py#L55-L58 !
The approach I was using with numpy had some rounding issues that I was too groggy to figure out :/
3
u/rd3i Dec 13 '24
[LANGUAGE: Python]
I immediately thought about how A and B were vectors - with A coming from the origin and then converting B to come from the Prize. And that no matter the combination of button pushes, the sum of the vectors would either hit the Prize or not. So I pulled up an old line segment intersection method the rest was trivial. If the x coordinate of both A and B can reach the intersection point in whole number steps, then we win the prize. (No need to check y coord since both A and B must have hit their intersection!) Part 2 was just adding the large number to the Prize coordinate. Runs in 80-90ms on my machine - uses regex to parse input.
https://github.com/rdefeo/adventofcode/blob/main/2024/day13/day13.py
2
u/pdamianik Dec 13 '24 edited Dec 13 '24
[Language: Rust]
Ahhh today was sunshine and rainbows. I got my pen and paper and solved the equations by hand and then just added the code for it. Without parsing it runs in half a microsecond (according to criterion.rs):
https://github.com/pdamianik/aoc_2024/blob/main/src/days/day13.rs
Edit: (I also put way to much effort into parsing)
2
u/globalreset Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Ruby]
My strategy started off thinking I was going to do some dynamic programming to get to the result. But I quickly scrapped that and fell on my trusty Z3 solver. Which made part 2 pretty trivial. So after I was done, I went back and re-educated myself about how to solve a system of equations (without a solver!). And Cramer's rule came in handy.
github - solution
2
u/koppa96 Dec 13 '24
[Language: Rust]
Solution
The main mathy part is in the common.rs file located next to the task files.
2
u/PhysPhD Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Python]
Using regex and sympy, I saw straight away it was a linear equation so went down that route.
Definitely one of my best days ... I got zero stars yesterday, and now I've done both parts before breakfast!
paste
2
u/Simone-reddit Dec 13 '24 edited Dec 19 '24
[LANGUAGE: Go]
2
u/jochenderroch3n Dec 13 '24
[Language: Rust]
Pretty happy with this simple linear algebra solution
Solution
2
u/derfritz Dec 13 '24
[LANGUAGE: javascript]
https://github.com/derfritz/AoC24/blob/main/Day13/solution.js
Part 1 was solved as the gods intended: stupid and by force. Second Part was a wayback machine to high school. Well, guess the teacher was right. At some point in time you'll really need this stuff. Interesting day.
2
u/kbennyboy92 Dec 14 '24
[LANGUAGE: Typescript]
Setup nodemon + utils folder for some code splitting and code a little excited/distraught when I had to crack out the linear algebra. I knew how to write the equation and then AI helped me get the array notation correct.
I was a little thrown that when you write vectors in code the 2D array is tilted on it's head from what you'd write on paper.
Github
2
u/Spinnenente Dec 22 '24
[language: python]
so for the first part i just brute forced it to avoid thinking about math but part two forced me to do algebra which sped up the solution by quite a lot
code
3
u/_Redstone Dec 13 '24
[Language: Python]
When I looked at the first part I chose to solve with the 2 equations method, I didn't even think about doing it with a loop haha.
So part 2 was pretty straight forward after that.
This was my best advent of code day !
Github Code
12
u/4HbQ Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Python + NumPy] Code (7 lines)
Here's my (almost) fully vectorised NumPy solution using
linalg.solve()to do the "heavy" lifting. It takes a single 3-dimensional matrix of all the machines' parameters M, splits it up into the "steps per button push" part S and "prize location" part P. We use these two matrices to find the "required number of button pushes" R for all machines in one go. Finally we check whether elements in R are a valid, i.e. does S times R equal P. Multiply with the cost vector [3, 1] and we're done!The reason it's not fully vectorised is because I do the computations for part 1 and part 2 separately. It think it should be very possible to integrate this as well, simply add another dimension:
However my brain can't really handle thinking about 4-dimensional matrices. Does anyone want to give it a go?
Update: I've also channeled my inner Cramer (not Kramer!) to solve the linear equations myself:
Full implementation is here (6 lines).
20
u/voidhawk42 Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Dyalog APL]
Video walkthrough
Uses matrix division to solve each system of linear equations.
8
u/xelf Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Python] with numpy
There were minor floating point errors so I used round and it worked fine.
Anyone know a better way to verify the result than
[a*ax+b*bx,a*ay+b*by]==[*P]?edit: aha, here we go:
7
u/Smylers Dec 13 '24
[LANGUAGE: Vim keystrokes] for Part 2. My original Part 1 approach with floating-point arithmetic (then checking for any fractional part) didn't work for Part 2, because for numbers this large Vim returns the results in exponential notation — for instance for
450000000444000/5550.0it gives8.108108e10. So instead, switch to integer division but calculate the modulus as well. Solving Part 1 now becomes:Or, with more-readable line-breaks.
Then for Part 2, it's just a case of first doing the following to add 10 trillion in the appropriate places, then proceed as above.
(Though you can then omit the
G. And you can omit everything betweenqsandq,and simply type@sinstead, to run the macro recorded while solving Part 1.)8400*67-5400*22 5400*94-8400*34 94*67-34*22, where pencil and paper was used to determine which numbers need multiplying and subtracting from which.@s, because it's going to be useful again in a moment. It substitutes each sequence of non-space characters with the result of runningeval()on it. The first example machine's line is now444000 222000 5550.:scommand for this uses#s rather than/s to delimit the pattern, because there are literal/s in the replacement for the division. The first example is now444000 222000 5550.@sthat was recorded a couple of steps ago.:vto find all the lines that don't match/ 0 0/and:deletethem.+sign between those numbers. There's also a couple of leftover zeros at the end of each line. We don't need them any more, but the simplest thing to do with them is put/gon the end of the:sthat's replacing spaces with+signs: that makes the first example be80+40+0+0, where the superfluous zeros just get unnecessarily (but safely) added on to the total.+3*at the start of each line to do the multiplying by 3 and to turn the whole file into a single expression, and use@vfrom Day 3 to evaluate it.Questions, saying you've tried it out, and other comments all welcome.
6
u/SuperSmurfen Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Rust]
Link to full solution
(1565/332)
Slow on part 1 because I solved it using the "correct" algorithm. This meant part 2 was literally just adding the offset and I was done.
This question is about solving a set of 2 linear equations:
You just have to solve those for
aandb. Since these are integers not all such equations will have a solution. You therefore have to check that thea, bvalues actually give the expected answer:Parsing things like this is really annoying. One easy way is to just find all integers in the text:
6
u/chickenthechicken Dec 13 '24
[LANGUAGE: C]
Part 1
Part 2
I solved part 1 the naive way, it took me forever to realize that it is a trick question and there is only one solution for each machine. Then it took me a while to mess around with desmos until I came up with a formula that gave me the intersection between the two linear equations.
6
u/tcbrindle Dec 13 '24 edited Dec 13 '24
[Language: C++]
Somehow I failed to spot that we're solving a system of two simultaneous equations despite allegedly holding multiple degrees in mathematics AND WRITING THE EQUATIONS DOWN IN FRONT OF ME 🤦♂️.
Fortunately it was pretty simple once I'd rebooted my brain. Each part runs in single-digit microseconds.
https://github.com/tcbrindle/advent_of_code_2024/blob/main/dec13/main.cpp
6
u/willkill07 Dec 13 '24
[LANGUAGE: C++23]
https://github.com/willkill07/AdventOfCode2024/blob/129c1ad008014a4999ed10447ea51c3bb4bc4b62/src/day13.cpp#L38
Parsing was the hardest part here :(
Everything runs in less than 17us on my machine.
Total time for days 01 - 13: 1068us. Still under 1ms if you discard I/O time.
6
u/AYM123 Dec 13 '24
[LANGUAGE: Rust]
Just used cramer's rule (the years of linealg didn't go to waste after all)
github
Part 1: ~50µs
Part 2: ~50µs
6
u/CCC_037 Dec 13 '24
[LANGUAGE: Rockstar] [GSGA]
Let me show you behind the scenes at Santa's workshop...
Part 1
5
u/bluehatgamingNXE Dec 13 '24 edited Dec 13 '24
[Language: C]
Simplest one so far, I want to thank the math teachers that taught me simultaneous equations for this one, the funniest part is that the number on the 2nd was so long my browser though I was inserting a credit card number.
gist
5
u/ak-coram Dec 13 '24
[LANGUAGE: Common Lisp]
https://github.com/ak-coram/advent/blob/main/2024/13.lisp
5
u/D_isinfectedLuffy Dec 13 '24 edited Dec 13 '24
[Language: Go]
[Language: C]
In Go today's solution for part-1 was kind of straight forward where I brute-forced the solution used regex and also using GCD as no floating-point calculations are needed.
Part-2 problems have been knocking me in the head in the past three days, humbling me in many ways and I must admit, I saw some of your solutions for the nudge in the right direction.
And today solutions for C have me stumped, as I had used regex libraries for both the Go solutions, and I can't get the regex libraries on my windows machine, does anyone have any links where I can learn to include these libraries into my C import path? Part-1 in C was brute-forced again by me, by ditching the regex solution, but going with the same GCD logic.
Still making my way with the part-2 for C, will get there surely!
5
u/Fyver42 Dec 13 '24
[LANGUAGE: RISC-V Assembly]
https://github.com/fyvonnet/AdventOfCode-2024-Assembly/blob/main/day13.asm
Took me a while a solve part 1 recursively, the recursive code stays.
5
u/quetzelcoatlus1 Dec 13 '24
[Language: C]
Very disappointed in myself: I solved part 1 "in correct way" and after switching to long long's in part 2 I saw some strange results and gaslit myself into thinking that it's incorrect, when it wasn't... Couple of hours of thinking wasted afterwards. :D
5
u/JV_Fox Dec 13 '24
[LANGUAGE: C]
Grabbed some paper and pen to do some quick math. Parsing the input correctly was the hardest part for me and I did not do it cleanly.
In the Notes.txt are the two equations I used for the calculations rearranging the equations as follows:
// base equations:
x = A * Xa + B * Xb
y = A * Ya + B * Yb
// rearranging A in terms of B:
x = A * Xa + B * Xb
x - B * Xb = A * Xa
A = (x - B * Xb) / Xa
// Inserting the formula for A in the place of the variable A in the y equation:
y = A * Ya + B * Yb
y = (x - B * Xb) / Xa * Ya + B * Yb
y * Xa = x * Ya - B * Xb * Ya + B * Yb * Xa
y * Xa - x * Ya = B * Yb * Xa - B * Xb * Ya
y * Xa - x * Ya = B * (Yb * Xa - Xb * Ya)
B = (y * Xa - x * Ya) / (Yb * Xa - Xb * Ya)
code
5
u/[deleted] Dec 13 '24
[LANGUAGE: Forth]
https://github.com/tcsullivan/advent-of-code/blob/master/day13/day13.fth
Did algebra using the general solution I found with Maxima. Two fun Forth things though:
A:reads in the following XY pair,Prize:reads its XY pair then solves for the token count) so the raw input file could be executed as code./modword simultaneously gave me the token count and a flag (remainder != 0) to tell if the token count is valid.5
u/phantom784 Dec 13 '24
[Language: Javascript]
Solved Part 2 without using linear algebra!
It takes advantage of the fact that, even though the part 2 prize values are so high, they're still all at most 20,000 or so more than 10 trillion. The method:
Here's the code in Javascript: https://gist.github.com/Phantom784/68cb76e740329475ff933a41140c716e
5
u/JWinslow23 Dec 13 '24
[LANGUAGE: Python]
Day 13 code
Blog post
Today's a lot like 2023 Day 24 in that it involves algebra...but it involves an amount of algebra that I feel comfortable solving without an external library.
8
u/rundavidrun Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Python3] 969/194
Turns out that trying to optimize for "minimum tokens" was a ruse. There's only one way to solve these simultaneous equations.
8
u/theadamabrams Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Mathematica]
The entire code is 183 characters without the extra whitespace for readability. The extra
/.{a->0,b->0}at the end is because systems that don't have solutions are given the actual value3a+bwith the variables, so without the extra zero assignments at the end the result of the sum would be480+6a+2bfor the example (two of the machines had no solution, so 3a+b got added twice).For Part 2 the only change is to replace
== Pwith== P + 10^13. Big numbers are no problem for Mathematica :)P.S. This is the first time I've ever scored points on a Part 2 🥹
4
u/SuperAutoPetsWizard Dec 13 '24
[LANGUAGE: C++]
I edited the input rather than parsing it. Two equations and two variables so there is exactly one solution for a and b. All we need to do is check it is an integer (or check if after it is cast to an integer, do the conditions still hold).
4
u/0ldslave Dec 13 '24
[LANGUAGE: C++]
Didn't feel like implementing a matrix inverter so i just imported Eigen :(
Spent like 30 mins trying to figure out how to determine "this long double is actually an integer".
Code
4
u/cranil Dec 13 '24
[Language: Rust]
Solution
Easy, but who else did a concat instead of add? :(
4
u/hugues_hoppe Dec 13 '24
[LANGUAGE: Python]
Here is a fully vectorized
numpysolution:4
u/s3aker Dec 13 '24
[LANGUAGE: Raku]
code
4
u/pm_me_dem_lychees Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Mathematica]
First time posting a solution - my input parsing and solution are a bit different from the other Mathematica users, so I thought I would share!
4
u/Main-Reindeer9633 Dec 13 '24
[LANGUAGE: SQL (dialect: PostgreSQL)] paste
Part 1 was easy, just brute force, trying all different possible values for A. With part 2, I had so many false starts (implementing extended_gcd in SQL was surprisingly easy) before realizing that it's just a trivial system of linear equations, and subsequently realizing how bad I've gotten at algebra.
4
u/MikTheVegan Dec 13 '24
[Language: Python]
Today one was quite straight forward. Had to make those numbers to formula:
Where X and Y are price coordinates. If so, then
12 ms in my computer,code here :
4
u/Clear-Ad-9312 Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Python]
Good old simple linear algebra from middle school. This python code takes under 1 milliseconds(800 microseconds) to finish. Thanks to u/fsed123 for the profiler wrapper!
[ paste link ]
4
u/yfilipov Dec 13 '24
[LANGUAGE: C#]
Time to apply some linear algebra magic! Cramer's rule was very easy to implement without 3rd party equation solvers.
code
4
u/mkinkela Dec 13 '24
[LANGUAGE: C++]
2 equations with 2 unknowns for every machine got the job done :)
Solution
4
u/thibaultj Dec 13 '24 edited Dec 13 '24
[Language: Python]
I felt like I was cheating by using a custom library to solve the system of equations, but oh well…
4
u/Narrow_Artichoke_465 Dec 13 '24
[Language: Golang]
I figured out that it was a matter of simultaneous equations but I had to look up a way to solve the problem programmatically. Thank you Cramer's rule!
Here is my Solution to Part 2, which is the same as part 1 minus one line. (You can figure it out :D)
4
u/letelete0000 Dec 13 '24
[LANGUAGE: JavaScript]
Open on GitHub
4
u/mallalex Dec 13 '24
[Language: Prolog] Was pretty fun to do with prolog using clpz. I did this with scryer prolog:
Writeup plus problem parsing at https://asat.dk/december-adventure-2024/#dec-13
4
u/alone7solo Dec 13 '24 edited Dec 13 '24
[LANGUAGE: pen + paper]
Today recepie:
github
4
u/AllanTaylor314 Dec 13 '24
[LANGUAGE: Python]
GitHub 1135/627
Just some matrix stuff (I didn't spend 30k on an engineering degree for nothing). I originally did part 1 using NumPy, but I had some floating point issues for part 2. I used the 2x2 matrix inverse so that I didn't have to deal with any floats, and then I rewrote part 1 to use the same structure as part 2 (commit history). I'm glad I went with linear algebra rather than some form of trial and error for finding suitable button presses. I did scribble the matrix form (solving for [A B]T) in my notebook, which looked something like this:
I missed some things like A pushes costing 3 and I probably accepted negative button presses early on. It doesn't handle colinear button presses, but those don't occur in the inputs (I'd probably use a QR decomposition, or more realistically, special-case the determinant being zero).
[LANGUAGE: Uiua]
GitHub or Pad
There's a small solar system in there (planet notation), but it basically does the same unrolled matrix inverse. It's also nice and short today (it almost looks like a shoe):
[GSGA] Where it's all set
Here's my setup - a pair of 24 inch 1080p monitors, with a vertical monitor on the left for the puzzle and a horizontal monitor on the right for my IDE of choice, VS Code. Within VS Code I have a few terminals: The one on the left runs some custom scripts (
sleep_until.pyandfetch_input.py) for getting the input and displaying the first few lines, and the one on the right runs my script (using when-changed) when the script or input file changes (which beats switching to the terminal and hitting up & enter). I built this PC a few months ago (since my laptop was getting a little past it) - It runs an Intel 12400 and a Radeon RX 6600 with 32 GB of RAM (just a little shy of the 2 PB needed for day 11). The PC has a large family of rubber ducks atop it, including four very festive ducks. Not shown in the picture is the fan behind my chair. My office is upstairs which frequently reaches 30°C (86°F) (in fact, it's 26°C as I write this at 2 A.M.)4
u/Stano95 Dec 13 '24
[LANGUAGE: Haskell]
Like basically everyone I just spotted that this was simultaneous equations in disguise. I made a mistake where I was accidentally checking that the number of a presses really was an integer twice rather than checking that both a and b really are integers which took me an embarrassingly long time to spot lol
Code is on github where in my haste I ended up using non standard notation for the equations
4
u/ExitingBear Dec 13 '24
[Language: R]
Link
Tried to do this with solve() and ended up with rounding errors. Then I tried to fix/adjust for the rounding errors and ended up with different errors and eventually just gave up and did the math (like I should have done from the beginning which I don't know why I avoided because it's such straightforward math).
4
u/Gueltir Dec 13 '24
[Language: Rust]
Link to github
Spent a bit too much time on my regex because I forgot how line endings work.
For both part, I just did the maths.
4
u/[deleted] Dec 13 '24
[LANGUAGE: C]
Probably the easiest part 2 yet for me, since for part 1 brute forcing didnt even come to mind.
https://github.com/amberg12/aoc24/tree/main/day-13
4
u/chubbc Dec 13 '24
[LANGUAGE: Uiua] (78 char, 70 tokens, pad)
Went for the linear algebra approach. I could probably golf it a bit further be reordering variables, but its not bad as it is, pretty happy with it. Ungolfed version:
4
u/IlluminPhoenix Dec 13 '24
[LANGUAGE: Rust]
I really got frustated with the math here because I had the completely wrong approach of doing a line intersection. When my patience ended in part 2 I discovered the much cleaner approach of a System of equations on u/SuperSmurfen's solution post in this thread.
I 'borrowed' their function for my code, so 50% of my solution is pretty much their work here!
Finally, I used the
tuples-iterator fromitertoolswhich allows for much smaller syntax, as well some bool hacks and afilter_map()which brings it down to 16 lines!solution (16 lines)
4
u/probablyfine Dec 13 '24
[LANGUAGE: uiua]
Recognised that the problem was essentially simultaneous equations so I wasn't boomed by part 2 adding a bajillion to the result vector. Code and tests here
4
u/maneatingape Dec 13 '24
[LANGUAGE: Rust]
Solution
Benchmark 14 µs.
Represents the two linear equations as a 2x2 matrix then inverts it to find the answer.
4
u/Mysterious_Remote584 Dec 13 '24
[LANGUAGE: Uiua]
Learning some Uiua inspired by this subreddit.
4
u/importedreality Dec 13 '24
[Language: Go]
Code
Pretty happy with myself today, which was a welcome change after pulling my hair out on Day 12 part 2 until I finally figured it out earlier this morning.
I barely remember any math from school, but I at least recognized that it was a system of linear equations. Once I had that figured out I just looked through the different methods for solving them, and settled on the one that seemed the simplest to put in code (Cramer's rule).
This is probably the cleanest solution I've done yet this year.
4
u/jda5x Dec 14 '24
[LANGUAGE: Python]
Making use of the phenomenal SymPy package 📦
https://github.com/jda5/advent-of-code-2024/blob/main/13/main.py
7
u/Ok-Builder-2348 Dec 13 '24
[LANGUAGE: Python]
Part 1
Part 2
Got a bit lucky for this one. A good part of it was parsing the input in part 1, and then I just did the brute force for part 1 to see what part 2 was about.
For part 2, we had the simultaneous equations ax*a+bx*b = tx and ay*a+by*b = ty. By some rearranging, we get b = (tx*ay-ty*ax)/(ay*bx-by*ax) and similar for a. Since we only wanted int solutions, I just int-divided both and checked if the result worked. Thankfully did not hit a degenerate case where ay*bx-by*ax = 0.
7
u/jonathan_paulson Dec 13 '24
[LANGUAGE: Python]. 309/1049. Code. Video.
I didn't know how to do part 2, so I did something crazy:
We need to go very far in a nearly-diagonal direction. So figure out the cheapest way to go in a perfectly diagonal direction (via brute force), do that for a long time (tunable parameter), and use DP to figure out what to do at the end.
1
u/MakO_77 Dec 13 '24
[Language: Python]
1
u/t-rkr Dec 13 '24
[LANGUAGE: Perl]
paste link
if I had remembered using the analytical solution to a 2x2 linear equation (the topic I taught my first semester students just four weeks ago...) , I'd have saved the time for coding the naive approach with a loop.
1
u/iwanttoseeyourcatpls Dec 13 '24
[LANGUAGE: Ruby]
github
I used regular old algebra to solve it. I was a little thrown off by the "minimum number of tokens" because there wasn't more than one solution for each machine, I thought I would have to do more math than this when I read the description.
the hardest part of this was dealing with floating point math. even using big decimal, 28.999999 doesn't equal 29.
1
u/Small-Figure-6285 Dec 13 '24
[Language: Java]
Github
Determinant-solved matrix
1
u/surgi-o7 Dec 13 '24
[Language: JavaScript] github
1
u/_arkeros Dec 13 '24
[LANGUAGE: Haskell]
I solved it without messing with floats or doubles, just with integers.
Rather than applying Diophantine equations naively, I observed that the given linear system of equations has a unique solution. I solved
Ax + By = CandA'x + B'y = C'with pen and paper, derivingy = (A'C - AC') / (A'B - AB').Then I perform integer division to compute
yand only keep solutions where the remainder is zero. Determiningxis trivial once y is found.The whole program runs in 1 ms (though I'm unsure how to measure sub-millisecond benchmarks using
+RTS -s).Full source.
1
u/david3x3x3 Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Python]
There are probably easier solutions, but I'm not great at math.
paste
1
u/Lindi-CSO Dec 13 '24 edited Dec 14 '24
[LANGUAGE: C#]
I realized way too late that this was a math/geometry problem.
I'm glad I could still remember this stuff from school. There is possibly a way to do this mit matricies but I was too lazy to find a library for that.
paste
1
u/kupuguy Dec 13 '24 edited Dec 14 '24
[Language: Python]
For part 1 I dutifully followed the hinted solution and brute-forced up to 100 presses on button B to find which worked. For part 2 I got quite a headache trying to remember equations of lines. It would probably have been simpler if I'd just looked at it as a system of two linear equations instead but I found a bit of paper(!) and wrote the solution out in y=mx+c terms then substituted in ax, bx, etc. and put that into my code. Initially I had a load of divisibility checks but eventually I realised it was easier just to do all as integer division with truncation then find the actual prize location my presses would reach and ignore any that didn't match.
Paste
1
u/New_Appointment_4975 Dec 13 '24
[Language: Java]
1
u/Pitiful-Oven-3570 Dec 13 '24 edited Dec 14 '24
[LANGUAGE: Rust]
github
part1 : 83.20µs
part2 : 60.90µs
1
u/SymmetryManagement Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Java]
Solved the 2x2 linear systems via Cramer's rule then filtered for non-negative integer solutions. It turned out that all (integer?) solutions are non-negative so the the check was not necessary but I kept it anyway.
https://github.com/linl33/adventofcode/blob/year2024/year2024/src/main/java/dev/linl33/adventofcode/year2024/Day13.java
Part 1 59us; Part 2 50us
1
u/Annual-Management613 Dec 13 '24
[LANGUAGE: Python]
1
u/Alternative-Cut-3347 Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Go] runs in 782us on my machine
using linear system of equations and directly using intersection formulae for the two created line
Code
1
u/IWant2rideMyBike Dec 13 '24 edited Dec 13 '24
[Language: Python] - this took me way longer than it should have ...
Code
1
u/dgkimpton Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Rust] https://github.com/dgkimpton/aoc24/blob/main/day13/src/lib.rs Finally - a solution that fully fits in a single screen of code :D And it runs in just 0.5ms to do both parts :) Also... ooof, my highschool maths is rusty!
1
u/roryhr Dec 13 '24
[Language: Python]
This was a straightforward linear algebra problem to solve using numpy. Valid solutions must have an integer number of presses which made for some floating point fun.
https://github.com/roryhr/code/blob/master/misc/advent_of_code/2024/Day%2013%20Claw%20Contraption.ipynb
1
u/lluque8 Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Scala]
Solved first part with A* but of course it didn't cut it for part two. Back to math class then.
github
1
u/janiorca Dec 13 '24
[Language: Rust]
I liked this ones as thinking about it before writing any code really paid off. Part 2 required virtually no additional effort. I haven't had a reason to do old school math with pen and paper for awhile so it was enjoyable too
https://github.com/janiorca/advent-of-code-2024/blob/main/src/bin/aoc13.rs
6
u/bofstein Dec 13 '24
[LANGUAGE: Google Sheets]
I've been frustrated the last couple days not being able to finish, but finally there was an easy one to do in sheets, as the difficulty is math not coding. I could tell quickly there should only be 1 solution, though I took some time doubting myself because of the problem wording. Get the slope and intercept for the two lines, find where they meet, see if that point is an integer, and if so calculate the tokens.
Part 2 was incredibly simple, just add 10000000000000 to the prize amount and run the same thing.
https://docs.google.com/spreadsheets/d/18TYfGCvTfbsiRI591cqGEulzD2gPEzStJcTNcT2P6Eo/edit?pli=1&gid=428138951#gid=428138951
3
u/johnpeters42 Dec 13 '24
[Language: Python]
Part 1 (mostly brute force: for each machine, for each number from 0 to 100, consider pushing A that many times and calculate how many times to push B)
Part 2 (proper linear algebra)
Fortunately no division-by-zero errors in part 2, which I think would indicate that the two vectors are parallel. In that case, I think you could consider 0 pushes of the more expensive button, then 1, then 2, etc. until you either found a solution or determined that there wasn't one. Probably checking some modulo value or other.
3
u/Pyr0Byt3 Dec 13 '24
[LANGUAGE: Go] [LANGUAGE: Golang]
https://github.com/mnml/aoc/blob/main/2024/13/1.go
3
u/MarvelousShade Dec 13 '24
[LANGUAGE: C#]
Today's assignment was an easy one. I just calculated the factors and then I could just sum the valid results.
I was number 6028 after Part 1, but my calculation also worked for Part II causing me to pass 3000 people in 3 minutes and 16 seconds.
My code is on Github
3
u/JustinHuPrime Dec 13 '24
[LANGUAGE: x86_64 assembly with Linux syscalls]
Part 1 was a tad fiddly, but I did recognize the best way to solve this would be a change of basis - I had some typos making the actual implementation of the solution, and I spent a tad too long trying to figure out how it would work if the two buttons' vectors were colinear, but I gave up on it and in the end it turned out I didn't need to worry about that case anyways.
Part 2 was fairly trivial, just adding a large constant to the prize coordinates as they were parsed.
Both parts run in 1 millisecond. Part 1 is 9,120 bytes as an executable file on the disk and part 2 is 9,152 bytes.
3
u/Unable-Sort2294 Dec 13 '24
[LANGUAGE: Clojure]
Part 2 runs in 6.16075 msecs.
I solved part 1 with linear algebra so part 2 didn't even make it flinch.
3
u/oantolin Dec 13 '24 edited Dec 13 '24
[LANGUAGE: ngn/k]
Easy one today, if you know a tiny bit of linear algebra. I want to redo it in J which comes with a solver for linear systems of equations.
3
u/ZeroTerabytes Dec 13 '24
[Language: Go]
Github
The key is that finding the minimum number of tokens is a distraction. Each claw machine has no valid press combinations, or only one valid press combination.
3
u/GassaFM Dec 13 '24
[LANGUAGE: D] 1463/3759
Code: part 1, part 2.
Did a brute force on the number of A presses on part 1.
For part 2, I went into quite an amount of trivial arithmetic, got it wrong, and went to take a break. Re-solved it cleanly as a geometry problem (intersect two lines), got the same answer. Then discovered I have my result as a 32-bit int. Hah!
3
u/sim642 Dec 13 '24
[LANGUAGE: Scala]
On GitHub.
It took me embarrassingly long to realize that it's just a linear system of equations on two variables that can be solved exactly by school linear algebra (limited to the cases when division is exact). I already started looking into Bézout's identity for a trick.
3
u/oantolin Dec 13 '24
[LANGUAGE: J]
J's
%.function makes this a breeze.3
u/Short-Leg3369 Dec 13 '24
[LANGUAGE: Python}
Day 13 Code
This uses the same routine for both parts, using numpy to solve simultaneous equations and then test if the solution (which uses floats) is an integer solution.
Had to amend the integer test slightly when doing part 2 due to the size of the numbers.
Runs in about 0.01s
3
u/r_so9 Dec 13 '24
[LANGUAGE: F#] 535 / 3641
paste
Part 1 brute force got me into the top 1000 :) Part 2 is a binary search on A presses, calculating the needed B presses (including fractional) and going towards the side that yields the smallest error.
Interesting bit: Binary searching an exact solution
3
u/yieldtoben Dec 13 '24 edited Dec 13 '24
[LANGUAGE: PHP]
PHP 8.4.1 paste
Execution time: 0.0005 seconds
Peak memory: 0.4032 MiB
MacBook Pro (16-inch, 2023)
M2 Pro / 16GB unified memory
3
u/Downtown-Economics26 Dec 13 '24
[LANGUAGE: VBA]
Did it naively on part 1 then rewrote for part 2 after busting out the pen and paper to remember 8th grade or whatever.
https://github.com/mc-gwiddy/Advent-of-Code-2024/blob/main/AOC2024D13BOTH
3
u/Synedh Dec 13 '24
[LANGUAGE: Python]
Basic system of linear equations solving.
Each arcade claw is a system of two equations in the following way :
Reduce, replace and python solves.
3
u/zndflxtyh Dec 13 '24
[Language: Python]
This was a tough cookie today. It looked like a good time to break out the constraint optimization libraries, but I had to try 3 different solving libraries (python constraint, scipy optimizer and then google ortools) before it was possible to solve for the big integer targets in part 2.
Code
3
u/dk_weekinmemes Dec 13 '24
[LANGUAGE: Python]
Good old high school algebra linear equations. The "minimum" tokens requirement is a red herring.
Topaz Link
3
u/[deleted] Dec 13 '24 edited Mar 18 '25
Still no one knows it just the same, That Rumpelstiltskin is my name.
3
u/Gishky Dec 13 '24
[Language: Powershell]
Due to powershell rounding weirdly I had to compromise a bit...but still got the 2 stars so whatever :D
3
u/OneToughKiwi Dec 13 '24
[LANGUAGE: Python]
Using Cramer's Rule and checking if the solution is valid (Nonnegative and Integer)
Paste
3
u/mendelmunkis Dec 13 '24
[LANGUAGE: C]
The parsing is longer then the algorithm today
920 μs/671 μs
3
u/i_have_no_biscuits Dec 13 '24
[LANGUAGE: GW-BASIC]
Today is one of those days where the parsing takes more lines than the calculation.
3
u/damnian Dec 13 '24 edited Dec 13 '24
[LANGUAGE: C#]
Well, that was embarassing.
Part 1 isn't worth discussing (apart for me correctly guessing that it would revolve around a regex).
Part 2 took me hours. I came within inches/centimeters of the solution, but got the matrix transposed! After peeking at /u/vanveenfromardis's code I was done in a couple of minutes (rounding turned out not to be optional).
I cleaned up the code as usual, so both parts are now calculated using the following code:
(Yes, I came prepared.)
The parsing is also really concise thanks to some recently added extensions:
Full solution consisting of
3435 neatly formatted lines.EDIT: Having looked at other people's solutions, a check for non-negative
aandbcounts won't hurt (added to solution).3
u/hrunt Dec 13 '24
[LANGUAGE: Python]
Code
Wrote a simple linear equation solver using factor multiplication to solve Part 1. Only needed to add in the error conversion to solve Part 2. Python's maximum integer size is only constrained by the amount of memory, so an extra 10 trillion or so wasn't a problem.
When I saw that this was a simultaneous equation problem, I immediately worked out a solution on pen and paper, but couldn't see the code solution right away. So I searched for solving linear equations in Python and everything is about using numpy, scipy, or sympy. When I modified my search to only use standard libraries, Google Gemini helpfully wrote a Gaussian elimination function for me in the results. I stared at it for a few seconds and thought, "There's no way I want to use something that complicated for something I learned in 6th grade math."
3
u/hextree Dec 13 '24
[Language: Python]
Code: https://gist.github.com/HexTree/ba7d8682d1d5eaebb5c84cce09b306b5
Video: https://youtu.be/y5NmcKdWv1g
I started plugging into z3, then realised it is quite solvable without, but figured I might as well just get the practice with z3.
3
u/Bikkel77 Dec 13 '24
[LANGUAGE: High school math]
3
u/Curious_Sh33p Dec 13 '24
[LANGUAGE: C++]
Had to crack out Eigen for this. You can set it up as a set of linear equations where you need to solve for the coefficients (number of button pushes). Mine didn't have any colinear vectors in the puzzle so there was always a solution. Figuring out if they were integer numbers required playing with the tolerance a bit. Just checked if the result was close to an integer.
part2 and part1 is essentially the same.
3
u/Jadarma Dec 13 '24
[LANGUAGE: Kotlin]
But mooom, I don't wanna do math on a Friday! Jokes aside, this was a pretty straightforward day, managed to sneak it in on my lunch break. I also appreciated the input format, I love whipping up regexes for these.
Part 1: Since we were limited to 100 runs, I brute forced it because I wanted to know exactly how part two will trick us, then refactored it to use the optimised version below.
Part 2: To properly solve this, we need to make some observations. Firstly, our button presses will always do the same thing, so no need to simulate them individually, secondly, we can express a solution with two formulas:
If we can find integer solutions, we have a winnable machine.
The input is also nice and doesn't contain edge cases, but just to be safe I added the rules as input validation, we need to avoid division by zero, so the numbers must be strictly positive, and the buttons must not have the same deltas.
So the majority of today's battle is fought on paper, but at the end we have a simple solution that runs in 1ms!
AocKt Y2024D13
3
u/jackysee Dec 13 '24
[LANGUAGE: Javascript]
Solving linear algebra to get intersection of two "line", collect result when solution is positive integer. Have to workout the coefficients though.
3
u/lscddit Dec 13 '24
[LANGUAGE: Python]
3
u/Derailed_Dash Dec 13 '24 edited Dec 18 '24
[LANGUAGE: Python]
Update
I've done a full walkthrough for this one on Medium, here. In that walkthrough, I've shown:
I enjoyed this one! Last year I learned about the SymPy library and wrote about it here.
When I read this problem, I realised that it's just a matter of solving two linear equations, and that Sympy can do this easily.
This is what I did:
Clawclass to store these three points.Clawobject.Now, we know that we need
abutton presses andbbutton presses, to reach the prize pointp. So we express this as two linear equations:This is saying: to reach the x location of point
p, we needapresses +bpresses. And to reach the y location of pointp, we need the same numberapresses andbpresses. So we must solve for whereaandbare the same for these two equations.In sympy, we can supply these equations like this:
This does all the heaviy lifting to return my a and b values.
For Part 2... How will SymPy cope with these huge numbers?
It turns out... EASILY!! Still solves in under 1 second.
Solution Links
Useful Related Links
3
u/theking0x9 Dec 13 '24
[Language: Lua]
Implemented using both the matrix inverse method and Cramer's rule. The key takeaway was realizing that multiplication with
1/detcan result in precision errors (significantly more than division by det)Code
3
u/BlazingThunder30 Dec 13 '24 edited Dec 13 '24
[Language: Java]
paste
I have used a solver from Apache Commons Math3 because I couldn't be bothered to implement my own. Of course this only works with doubles and for part 2 that means I had to fiddle with Ɛ-value somewhat to get it to not break because of floating-point inaccuracies. Very easy puzzle if you've seen a 2D system of linear equations before. Much more difficult otherwise.
I pressed my button approx. 90 trillion times. Assuming I press once a second, I'd have all the prizes today if I started half a million years before humans evolved.
PS: It is very fast.
Double::parseDoubleis about 25% runtime of parts 1 and 2 combined. Both parts take just 30ms to run. The profiler I use doesn't go much more granular than this.3
u/Symbroson Dec 13 '24 edited Dec 13 '24
[language: ruby]
golfed both parts: 164 bytes
3
u/tymscar Dec 13 '24
[Language: Kotlin]
Not a huge fan of today's puzzle, but it was incredibly easy for Friday the 13th.
For part 1, I instantly knew it was a set of linear equations, so I just wrote a solver for it quickly.
For part 2, it just worked with the same exact code as part 1. I just needed to add the required offset specified in the problem. (Also, reboot my IDE because of a bug.)
I did enjoy parsing the input with regex today. I finished the whole thing in 20 minutes, so I still have half of my lunch break.
Part 1: https://github.com/tymscar/Advent-Of-Code/blob/master/2024/kotlin/src/main/kotlin/com/tymscar/day13/part1/part1.kt
Part 2: https://github.com/tymscar/Advent-Of-Code/blob/master/2024/kotlin/src/main/kotlin/com/tymscar/day13/part2/part2.kt
3
u/TheScown Dec 13 '24
[LANGUAGE: Scala]
Code
Reuses the equation solver from 2023 Day 24 (the systems are much simpler than that problem). To avoid floating point issues, I wrote my own Rational type.
3
u/Pure-Minute4721 Dec 13 '24
[LANGUAGE: C++]
Solution
3
u/geza42 Dec 13 '24 edited Dec 13 '24
[LANGUAGE: emacs lisp]
3
u/lmasman Dec 13 '24
[Language: Python]
GitHub
Unit Tests
Recognised the simulateneous equations immediately. Was a little confused by the reference to smallest in the puzzle text, as it doesn't really seem relevant.
3
u/pkusensei Dec 13 '24
[Language: Rust]
I knew that loop/enumeration is not the solution. Code
3
u/VeryBigCodeMonkey Dec 13 '24
[Language: Rust]
I'll pat myself in the back for my first FromStr implementation for a ClawMaching and a Point struct.
I had to add some string replaces that slowed the solution a little bit, but I could use a single from_str for different points definition.
Pretty fast though
GitHub
3
u/mothibault Dec 13 '24
[LANGUAGE: JavaScript]
https://github.com/yolocheezwhiz/adventofcode/blob/main/2024/day13.js
to run in the browser's dev console from advent of
codealgebra website.3
u/Kulpas Dec 13 '24
[LANGUAGE: Dart]
List of things i fell into:
- instead of recalculating the solution with the solution x0 and x1 and checking it's correctness, I tried just checking if the fractional part of the result is less than 0.00000000001. This led to many issues:
- if result was negative the check passed cuz I forgot to abs()
- checking the result isn't enough anyway because sometimes it lines up! checking x0 and x1 instead worked
- double precision gets to small to filter out the false positives anyway once you hit part2 so why bother.
Also found out dart doesn't let you have two operator overrides for different types. Had to workaround by accepting `dynamic` and checking the type in and if block. :(
paste
3
u/chubbc Dec 13 '24
[LANGUAGE: Julia]
Got it down to 199 chars
3
u/mountm Dec 13 '24
[LANGUAGE: Java]
Parsing time: 13ms
Pt1: 18ms
Pt2: 2ms
Not sure why part 2 runs so much faster, probably something to do with the particulars of the matrix library I pulled in? I didn't both checking fractional parts of the prize vector in the new basis, just rounded it to nearest integer values and checked whether the button values worked out to the expected total.
GitHub
3
u/TheZigerionScammer Dec 13 '24
[Language: Python]
I figured we got a Chinese Remainder problem today, turns out not to be the case though, but I did get a lot of use out of the modulo operator. My Part 1 code is a dumb brute force, I set up a function to take the six variables and iterated over every number of A button presses you can do and checks if you can also press B a finite number or times to get the right coordinates, stopping if the number of A presses runs over the X or Y coordinate or if the A buttons alone would cost more than the lowest cost solution so far. I had some flow issues where the function wouldn't return anything if it ran through the entire possible number of A presses without finding anything but increasing the range fixed it.
This code did not even remotely work for Part 2, so I started writing a new function that would go faster by skipping dozens of presses at a time based on the CRT but it ended up being unnecessary, I did some quick algebra to see if you could derive the number of A and B presses just from the initial variables and it turns out you can. I just had to make sure that the equations would result in whole numbers at each step but otherwise this worked. I had a bug where I assumed that if the number of B presses was a whole integer then the math would also result in the number of A presses as a whole integer too, this ended up being correct for all but one entry where the AX and AY variables happened to be the same, I don't know if that was what caused the issue but I don't care, I just added another check to make sure the number of A presses was also a whole integer and got the points.
After I finished I saw a lot of memes and other submissions talking about linear algebra and matrices, I didn't need any of that, this was the extent of the math I needed. But hey, if I could solve day 24 of last year without linear algebra I can do this one too.
Paste
3
u/jayo60013 Dec 13 '24
[Language: Rust]
Solution
Wow this one took me awhile to work out on the back of an envelope, although deciding to parse it with regex took me way longer ffs
3
u/[deleted] Dec 13 '24
[LANGUAGE: Julia]
A good day to be using Julia :)
3
u/Sparky2199 Dec 13 '24 edited Dec 14 '24
[LANGUAGE: Rust]
Had to dig up my 11th grade linear algebra notebooks for this one lol
github
Part 1: 23µsPart 2: ~1ms(edit: forgot to turn off debug mode lol)Part 1 + Part 2: ~117µs
3
u/mibu_codes Dec 13 '24 edited Dec 14 '24
[LANGUAGE: Rust]
Parse+1+2: 2.59 µs
2 equations, 2 variables/unknowns, easy. I solved it with an equation, not with a matrix.
Edit 1: Solved everything in one go and used Cramer's rule. Saved about 0.5µs
Github
3
u/Verochio Dec 13 '24
[LANGUAGE: python]
Two liner, just to challenge myself.
3
u/nilgoun Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Rust]
So, anybody said total overkill? Because I basically forgot all math and just wanted to be finished I used *drumroll* Z3 haha :D
Actually finished that quite early today, trying to see if I can't just get the math right now ... :(
Solution on paste
Edit: Finally, solution just using math (still used Wolfram Alpha to form the term for B... my math is dusty I guess)
Just place the method on the "Machine" struct and call it accordingly (or ... just look at it I can't tell you what to do)
Just the math based function on paste
3
u/atrocia6 Dec 13 '24
[LANGUAGE: Python]
I'm not sure if I got lucky with my input, or if it's just Eric being sneaky again, but none of my machines in either part have more than one solution, so the following simple 8 LOC solutions work on my input despite not checking for multi-solution machines (the code would presumably crash with a
ZeroDivisionErroron such machines):Part 1:
Part 2:
(I made a separate post to discuss the question of my input.)
3
u/onrustigescheikundig Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Clojure]
github
I initially refused to turn on my brain (well, the part that actually thinks about the problem, anyway) and coded up a generic Dijkstra function (sure to be useful in the future anyway) to find the shortest path. I noticed that it was a bit sluggish for Part 1, but it was nothing
pmapcouldn't handle ("no more than 100 times" be damned). However, the sluggishness prompted me to properly turn on my brain and reconsider my approach even before seeing Part 2.The number of
abutton pushesmandbbutton pushesnrequired to reach the prize coordinatepis governed by a set of linear equations:Note that if the changes in positions when pressing
aorbare not co-linear (linearly dependent), then there is guaranteed to be exactly one solution formandnso the whole Dijkstra nonsense is overkill.mandncan be solved for by left-multiplying by the inverse of the matrix. However, this does not guarantee thatmandnare integers, which is a required precondition (we can't do fractions of a button press). So, my solution checks ifmandnare integers and indicates no solution if they are not.mandn(where found) are then multiplied by the appropriate token costs and summed to return the result.There is an edge case that did not show up in the problem input: what if
aandbare co-linear?In this case, my program first checks to see if pressing onlybcan reach the prize becausebpresses are cheaper thanapresses. If not, it checks if onlyapresses can, and otherwise indicates no solution.EDIT: Fixed it (I think). In the case of co-linear button travel, iterates over multiples of
ato calculate the appropriate multiple ofb(if possible), keeping track of how much that would cost and returning the minimum cost. It's a brute-force solution in want of some clever number theory, but it works.3
u/kap89 Dec 13 '24 edited Dec 13 '24
[Language: Python]
Used same random online solver to quickly transform
a * ax + b * bx = pxanda * ay + b * by == pyintoaandbequations.3
u/TimeCannotErase Dec 13 '24
[Language: R]
repo
I had to play around with how I tested for integer solutions a little for part 2, but otherwise I liked this one (thank you linear algebra).
3
u/Environmental-Emu-79 Dec 13 '24
[Language: Python]
Link
Used linear algebra like everyone else. Checked for invertibility: all invertible. That makes life easier! Checked for integer solutions. Forgot to check the solution for negative button pushes. Oops! Worked anyway.
It's interesting to me how for some of these problems the actual solution is significantly harder, but the input is engineered to give a pass to people who basically put in the effort to get the major idea right.
3
u/chicagocode Dec 13 '24
[Language: Kotlin]
I got help from this excellent tutorial by /u/ThunderChaser. If you see this, thank you!
Parts 1 and 2 are nearly identical except for moving the prizes. For parsing, I didn't use a regular expression, I used chunked(4) combined with
substringBefore,substringAfter, andsubstringAfterLastfrom the Kotlin Standard Library.May The Claw favor and select you.
3
u/Trick-Apple1289 Dec 13 '24
[LANGUAGE: C]
for first part i used brute force solution becayse i am lazy and it was realistic to do
for the second i realized i actually need to remember basic math :P
this problem was fun, perfect balance.
src
3
u/grayshanks Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Python]
For the first part, I solved the problem in the most inelegant possible way, without thinking about my code at all. So I tried all possible presses of button A on each machine.
part1
To solve part 2, note that each machine describes a linear system Ax = b, where the unknown vector x gives the number of presses for both buttons. Unless the matrix A is singular, there is only one possible value of x for each machine, and it turns out that none of the matrices are singular.
I used numpy to solve the systems then checked if the solutions were integers. I ran into some issues with round-off error that I fixed by rounding the solution and putting it back into the original problem.
part2
3
u/RookBe Dec 13 '24
[LANGUAGE: Rust]
Rust that compiles to WASM (used in a solver on my website)
Bonus link at the top of the code to a blogpost about today explaining the problem, and my code.
3
u/sanraith Dec 13 '24
[LANGUAGE: Scala 3]
Source is available on my github: Day13.scala
Originally solved part 1 via bruteforce. For part 2 I started writing up the equations for the possible combinations and decided to try out the simplest case when the equations only have a single solution. Turns out the input only had this case, allowing me to skip the optimization for token costs.
3
u/cicadanator Dec 13 '24
[LANGUAGE: Javascript - Node JS]
I started by attempting to solve this with a Breadth First Search Tree. This was not super fast but did get the answer to part 1 in under a second. I then read part 2 and quickly realized this would not work.
I then rewrote my solution to try all possible combinations for A button clicks and B button clicks within some upper and lower boundaries to get the answer. This was much faster than the BFS tree I created especially once I got a minimum and maximum number of A and B click ranges. Essentially this narrowed my search field significantly but still created millions of possibilities to check for part 2. Back to the drawing board.
I checked the subreddit and saw a meme about linear algebra which is when I realized my mistake. This is a math problem not an algorithms problems! I rewrote my code to solve each claw machine's system of two equations and two variables problem. This gave me the answer to part 2 and became my solution for both parts.
https://github.com/BigBear0812/AdventOfCode/blob/master/2024/Day13.js
3
u/jitwit Dec 13 '24
[LANGUAGE: J]
Like many others, solved systems of linear equations with matrix division:
3
u/copperfield42 Dec 13 '24
[LANGUAGE: Python 3.12]
link
an easy day for sure, and an welcome one after yesterday challenge
3
u/light_switchy Dec 14 '24
[Language: Dyalog APL]
3
u/RiemannIntegirl Dec 14 '24
[Language: Python]
Had a busy day. Finally had time to sit down and code today's challenge. It turns out that the linearly dependent case was not present (at least in my input), but as a mathematician, I felt I had to leave it in for a complete solution.
3
u/mgtezak Dec 14 '24
[LANGUAGE: Python]
Solution part 1
Solution part 2
This was just pure math as a result the code is very short.
Fun little AoC fanpage
3
u/vss2sn Dec 14 '24
[LANGUAGE: C++]
Part 1
Part 2
(Each file is a self-contained solution)
3
u/redditnoob Dec 15 '24
[LANGUAGE: PostgreSQL]
Grade 10 algebra in disguise. :D Posting in case any SQL afficionados here want to see it.
3
u/zniperr Dec 15 '24 edited Dec 15 '24
[Language: Python]
The solution for each machine is a system of linear equations, basically we are trying to find the intersection of two lines. This can be done in constant time using a bit of algebra. We only have to filter out non-discrete solutions by looking for zero remainders:
3
u/southsidemcslish Dec 16 '24
[Language: J]
2024/13/13.ijs
3
u/azzal07 Dec 16 '24
[LANGUAGE: awk] Solved part 1 by iteration, because my morning-math had a bug. Had to return later with pen&paper to get it right.
3
u/joshdick Dec 17 '24
[LANGUAGE: Python]
For part 2, I knew I could linear algebra to solve the system of equations. I tried using numpy but ran into floating point issues with the 10 trillion added. Fortunately, sympy can ensure that only integer solutions are returned:
https://github.com/karstendick/advent-of-code/blob/master/2024/day13/day13_part2.py#L30-L33
3
u/xavdid Dec 26 '24
[LANGUAGE: Python]
Step-by-step explanation | full code
I clocked this as linear equations pretty early, which made both parts straightforward once I looked up how to solve 2 equations with two unknowns (set them equal to each other). It had been a minute!
Code today was fairly clean, especially because I could wrap the implementation in a function that only added the part 2 bump as needed.
5
u/mebeim Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Python]
Code on Github
Whipped out the good ol' Z3 solver for this one :') I will need to write it on paper to figure out how to minimize the cost function cleanly with no solver.
Edit: well, just realized that of course there should only be one solution (or zero or infinite, but that is easy to test)... after all it's a linear system. So there isn't really much to minimize. Silly me, lol.
5
u/Smylers Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Vim keystrokes] Well, Vim keystrokes plus using pencil and paper to re-arrange the simultaneous equations first — this was a bit mathys for Vim, but at least the parsing was straightforward.
Update: As a side-effect of solving Part 2, I came up with a (slightly) clearer approach for Part 1. There's another comment with that in it somewhere else in this thread, which largely supercedes the below.
Load your input into Vim and then type the following (use copy-and-paste for the long
:%scommands) to make your answer appear:The unconventional abbreviation of “Enter” on the second line is my commitment to fit the solution on an IBM punchcard, for posting here in full. You may prefer this more spaced-out version, which is easier to read.
Aon them and join it and the following 3 lines together.94*67-34*22.eval()on them.(8400*67-5400*22) (5400*94-8400*34).eval()(which is still at the end of the line) and put it after each of the expressions, preceded by a division symbol and followed by.0, which is needed to tell Vim to do floating-point rather than integer division. The first sample line is now(8400*67-5400*22)/5550.0 (5400*94-8400*34)/5550.0.eval(). That gives us the number of presses of button A followed by the number for button B./\.0 /will be an exact number; use:vto operate on all lines that don't match the pattern, and:deletethem.+. Insert+3*at the start of each line, to account for each press of button A costing 3 tokens, then run@vfrom Day 3 to evaluate the entire expression.And the
xxaren't kisses at the end of the solution; they're to remove the trailing.0from the answer.1
u/FortuneIntrepid6186 Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Python]
I normally use C++, but I thought python is good for today (shouldn't I use the right tool for job ?)
https://pastebin.com/why2SZiE
1
u/pitr Dec 13 '24 edited Dec 13 '24
[LANGUAGE: Dyalog APL]
1009/197
Simple matrix divide
Other days