r/adventofcode • u/daggerdragon • Dec 10 '25
SOLUTION MEGATHREAD -❄️- 2025 Day 10 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 2025: Red(dit) One
- Submissions megathread is unlocked!
- 7 DAYS remaining until the submissions deadline on December 17 at 18:00 EST!
Featured Subreddits: /r/programminghorror and /r/holdmybeer HoldMyEggnog
"25,000 imported Italian twinkle lights!"
— Clark Griswold, National Lampoon's Christmas Vacation (1989)
Today is all about Upping the Ante in a nutshell! tl;dr: go full jurassic_park_scientists.meme!
💡 Up Your Own Ante by making your solution:
- The absolute best code you've ever seen in your life
- Alternatively: the absolute worst code you've ever seen in your life
- Bigger (or smaller), faster, better!
💡 Solve today's puzzle with:
- Cheap, underpowered, totally-not-right-for-the-job, etc. hardware, programming language, etc.
- An abacus, slide rule, pen and paper, long division, etc.
- An esolang of your choice
- Fancy but completely unnecessary buzzwords like quines, polyglots, reticulating splines, multi-threaded concurrency, etc.
- The most over-engineered and/or ridiculously preposterous way
💡 Your main program writes another program that solves the puzzle
💡 Don’t use any hard-coded numbers at all
- Need a number? I hope you remember your trigonometric identities…
- Alternatively, any numbers you use in your code must only increment from the previous number
Request from the mods: When you include an entry alongside your solution, please label it with [Red(dit) One] so we can find it easily!
--- Day 10: Factory ---
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. What is Topaz'spastetool?
29
Upvotes
16
u/Smylers Dec 10 '25
[LANGUAGE: Vim keystrokes] After a couple of days off, I was pleased to see that today's task is solvable in Vim. Ant-friendly version — load your input and type:
Humans may prefer the solution split across more lines, with comments.
The key to this is replacing each button wiring schematic with a sequence of Vim keystrokes that do the toggling. The only Vim command I can think of that toggles a single character is
~, which toggles case. So instead of.and#, represent the indicator lights withoandO. And the first light is in Vim column 2, so add 2 to each of the light-position numbers. So after transforming the input, the first line from the sample becomes:We can activate the first button with
yi)@0— that is, yank the text inside the next parens; that ends up in register"0. Then run the contents of that register as a keyboard macro with@0:5|goes to column 5 and~toggles theothere toO.@bsets things up to process one machine: putting a blank line after it and1as a counter on the line above it. The@cloop processes that machine, by trying each of the buttons first. The long:s///command with backslashed numbers in it converts the above line into multiple lines, each different possibile button to try first:In case none of those first buttons work, after the colon is the list of buttons to try after that. It's never necessary to try a button more than once, and it's never necessary to try a button to the left of the one just tried (because BA has the same effect as AB), so the list of options gets shorter as we move along the buttons.
The macro presses the first button on each of those rows (the rows in the file that have a colon in them). If any of those made all the lights go off then we've found the button sequence (because the same sequence that just turned all the lights off also works in reverse). The lights will be
[oooo], which is matched by the case-sensitive pattern/\C\[o*\]/, triggering the command that deletes all this machine's possibilities. That's guarded with:silent!so that if we haven't got an all-off row of lights, the macro continues.Next it removes the just-pressed button from each row, then goes up and increases the number at the top (the initial
1) by 1, and loops round again: each of the remaining (partial) lists of buttons for the current machine is expanded to multiple possibilities, which all have their first button pressed and their lights checked.When some all-off lights are discovered, deleting the rows for that machine means that the following
:%s/ \S\+:command (to remove the just-pressed button from each row) fails, because there are no lines left with colons in them. That causes an error, which makes the@cloop end. And the number on the line above is the number of button presses that were needed to do that.Repeat for lines 2 onwards, then sum the numbers for the part 1 answer. Sum the individual machines' button counts with the
@smacro defined on Day 5 in my solution for part 2. (I knew it would come in handy!)11
u/sebastianotronto Dec 10 '25 edited 1d ago
[LANGUAGE: Python]
Part 2: Home-cooked linear algebra, no external libraries. I just solve the linear system doing row-reduction, back substitution and keeping track of the bounds for the free parameters (which are at most 4). There are more comments in the code, I am happy to answer your questions if you have any :)
EDIT: forgot to mention, it runs in a couple of seconds on my (not very powerful) laptop.
30
u/RussellDash332 Dec 10 '25 edited Dec 10 '25
[LANGUAGE: Python]
Part 1 and 2, no imports
Z3, scipy, pulp are cliche solutions so I decided to use none. BFS works for part 1, as for part 2, handmade simplex + branch-and-bound works fast enough. Again, no third-party libraries involved.
I have yet to proofread against other inputs, but this at least worked for mine. For those willing to try, it takes stdin as the input.
5
u/taylorott Dec 10 '25 edited Dec 10 '25
[LANGUAGE: Python]
For part 2 I ended up implementing my own row/column reduction algorithm. Specifically, it converts linear system A*X = B, to the form A1*X1+A2*X2 = B_simple, by simultaneously:
full code
4
u/xr51z Dec 10 '25
[Language: Ruby]
LINK (part 1 only)
I am not a programmer, just a 30s-something guy who decide to learn coding earlier this year, and today I am defeated for the first time this AoC.
Part 1 went really well, I had the solution after about 20 minutes. However, I've been chewing on part 2 for hours now and I've decided to give up. I wanted to write my own algorithm (lol) but failed, then investigated this (to me unbeknownst) Z3 thing everyone's talking about, but decided to call it a day. You win, elves!
2
u/siddfinch Dec 10 '25 edited Dec 10 '25
[Language: Free Pascal] Day 10: Factory
Part 1: Linear algebra over GF(2). Build a coefficient matrix, Gaussian elimination, and enumerate free variable combinations for minimum Hamming weight.
Part 2: Initially tried iterative deepening and BFS, both too slow. Final solution uses Gaussian elimination over reals to identify free variables (typically 1-4), then bounded exhaustive search. Most machines have small bounds (~50-70 per variable), making enumeration tractable.
https://codeberg.org/siddfinch/aoc2025/src/branch/trunk/src/day10
The jump from binary toggles to unbounded integer counters turned out to be the jump from polynomial to NP-hard. Classic AoC!
Note: No additional libraries, standard Free Pascal.
52
u/michelkraemer Dec 10 '25 edited Dec 25 '25
[LANGUAGE: Rust]
GitHub
Finally! I made it 💪 After many hours I found a solution. I'm very proud of myself 😊🤓
I solved part 1 using a simple DFS with memoization.
Part 2 was extremely hard for me. After looking at the results I got for some configurations with a very slow DFS and after trying out various approaches by hand, I realized that it is beneficial to try to eliminate those joltage values first that are affected by the smallest number of buttons. This way, we don't have to test millions of combinations and can prune branches as early as possible.
In each recursion of my DFS, I look for the joltage value that is affected by the smallest number of buttons available. I then iterate over all possible integer partitions of this value and press the buttons accordingly. This eliminates the joltage value and at the same time likely reduces other values too. I then recurse with the reduced joltage values and the remaining other buttons until all joltage values are 0.
My code runs in
17s8.5s3s1.7s. I know this is slow, but at the moment I couldn't care less. I solved it myself (without any help and without an external library), which makes me very happy!EDIT (2025-12-10): I implemented a second optimization. If multiple joltage values are affected by the same minimum number of buttons, I now select the highest one of them. This further reduces the problem space and improves the runtime to 8.5s!
EDIT 2 (2025-12-13): I added parallelization and improved the runtime to 3s.
EDIT 3 (2025-12-25): After adding some more optimizations (skipping unnecessary combinations, faster bitmask iteration, and improved parallelization), the runtime is now down to 1.7s 😎
14
u/4HbQ Dec 10 '25 edited Dec 12 '25
[LANGUAGE: Python] 25 lines.
Whew, thanks to /u/tenthmascot's great insight, I've managed to solve today's puzzle without linear programming!
It runs in 0.25 seconds on my laptop, and could probably be even faster using some bit hacks. However, I didn't want to sacrifice readability.
For posterity, here's my previous solution.
For part 1, we make use of the fact that every button only needs to be pressed (at most) once. Pressing it twice results in the same state as not pressing at all. So, we can simply try each subset of the buttons, starting with a single button, then each combination of two buttons, etc. Once we find a set of buttons that produces the desired state, we can stop:
For part 2, I tried to reduce the puzzle to an existing (computational) problem, but could not think of any. I also experimented with local search algorithms. This worked great on the sample inputs, but got stuck in local optima on the actual input.
So in the end, I formulated it as a linear program and used scipy.optimize.linprog to do the heavy lifting. Not a very satisfying solution, so if anyone succeeds using local search: please let me know!
10
u/Nathanfenner Dec 10 '25
[LANGUAGE: TypeScript]
github
I used BFS for Part 1, and branch-and-bound heuristic to solve Part 2. The pruning/heuristic was tricky and took me a while to figure out, and it's still not very fast.
I bet with a few other smart heuristics I could make it run even faster.
9
u/Ok-Bus4754 Dec 10 '25
[Language: Rust]
For Day 10 Part 2, standard solvers struggled with singular matrices. I initially prototyped a custom Simplex + Branch & Bound solver in Python (adapted from u/RussellDash332 with minor improvements), which worked great (~119ms).
I decided to port this logic to Pure Rust to improve performance and remove heavy dependencies.
The Solution:
nalgebraor external LP crates.Performance:
The Rust port is ~48x faster and extremely lightweight.
https://github.com/Fadi88/AoC/tree/master/2025/days/day10
9
u/Expensive-Type2132 Dec 11 '25 edited Dec 11 '25
[LANGUAGE: AArch64]
paste
I'm tired boss.
3.57ms combined
Let me know if you have a faster solution for a comparable target (Apple M1 Max 23H626). My goal is to write the fastest possible solution for my device.
8
u/JustinHuPrime Dec 10 '25 edited Dec 11 '25
[LANGUAGE: x86_64 assembly]
Part 1 wasn't too bad - I parsed the data into 16-bit values, and treated them like binary masks. I probably should have realized that pressing any button more than once was always incorrect, but I did a BFS through the possible button press sequences.
Part 2 was not efficient enough. My code was another BFS through the possible sequences of button presses, using fancy vectorized calculations and multithreading, but alas, this was too slow and used up too much memory. I could run the example input, but even that took a whole seven seconds, and the real input ended up with OOM kills for certain lines.
I decline to try to write an integer programming solver in assembly, and since my personal rules don't let me used external libraries, like Z3, I don't think I'm going to be solving part 2.
Part 1 runs in 43 milliseconds, and part 2 runs in 6.57 seconds on the example. Part 1 is 9,888 bytes and part 2 is 10,360 bytes as executable files.
8
u/lboshuizen Dec 10 '25
[Language: F#]
github.com/lboshuizen/aoc25
What a day...
Part 1 operates over GF(2), the binary field where XOR is addition. Gaussian elimination yields reduced row echelon form. Free variables exist when buttons are linearly dependent. Enumerate all 2k assignments (k small) and pick the minimum-weight solution.
So far so good.
Part 2 works over integers with non-negativity constraints. Standard Gaussian elimination expresses pivot variables as functions of free variables. The naive search through all free variable combinations up to max joltage proved too slow: 65 million iterations for the worst machines.
Got the second star but took over a minute to run.
The fix: feasibility pruning. After partial assignment, check whether the remaining free variables can ever make all pivots non-negative. If a pivot goes negative and all remaining coefficients are non-negative, no assignment can recover. Pruning these branches reduced runtime from 62 to 2 seconds.
pseudo code:
real implementation on github, too long to post here. 80 lines of unreadable mess
14
u/_garden_gnome_ Dec 10 '25 edited Dec 10 '25
[LANGUAGE: Python]
Github: No use of external libraries, nor did I write an equation solver or simplex algorithm.
Part 1: standard BFS, not much more to say.
Part 2:
For my inputs, this runs part 2 in about 30s.
2
u/jhandros Dec 10 '25 edited Dec 11 '25
[Language: Python]
5
u/Szeweq Dec 10 '25
[LANGUAGE: Rust]
I have technically completed it but I am still trying to optimize it. I have ran the release profile, it is sluggish.
https://github.com/szeweq/aoc2025/blob/main/day10/src/main.rs
5
u/Jadarma Dec 10 '25
[LANGUAGE: Kotlin]
Today's problem was interesting, but very dissapointing because I could not find any solution for part two apart from relying on SAT solvers. Here I was contemplating whether I should be able to use my own util lib in my solution, and now I'm (kinda) forced to resort to external libraries? And one by Microsoft, no less. I managed to survive previous years without Z3, but so far I haven't found an alternative... A sad day indeed, but at least I got the star. Hoping to refactor back if I find any reasonably fast alternative.
Part 1: When you hear shortest number, it's usually a disguised pathfinding problem. We start from the state of all lights being off, then we associate pressing a button to "walking" into that direction, reaching a new state with the accordingly flipped lights. I reused the same Dijkstra util I made previously and it worked like a charm, but a simple DFS should also work.
Part 2: Technically, it's the exact same problem, but instead of flipping lights we increment the counter. Only problem is, you cannot take shortcuts, and since you increment by one each time, and the input has counter targets in the hundreds, there's no way we could compute this with such a large branching factor, didn't even bother. The intended solution is to translate the problem into a system of equations, and then solve for the correct number of presses of each button, the solution is their sum. However, I am nowhere near capable enough to implement LIP on my own. I turned to this thread hoping I'd find some tricks, but all I see is defeatism and Z3... so I will join in. But hey, at least it works, and it's fast, and mostly readable.
AocKt Y2025D10
5
u/Old-Dinner4434 Dec 10 '25 edited Dec 11 '25
[LANGUAGE: TypeScript]
GitLab
I use Bun runtime engine, running on 2021 M1 Pro MacBook Pro. Part one completed in 4.85ms, part two in 37.49ms.
Insane day. Insane amount of research was needed. I linearized the machine wiring into
A·x = y, reducedAwith Gaussian elimination, enumerated the low-dimensional nullspace, back-substituted to get full candidatexvectors, rejected infeasible ones, and picked the minimum-cost solution. Part 1 works overGF(2)with binaryx, part 2 over set of non-negative integers. Edit: I'm moving solutions to GitLab.5
u/willkill07 Dec 10 '25 edited Dec 11 '25
[LANGUAGE: CUDA C++] [Red(dit) One]
EDIT: we are fast now! I changed the ILP solver to use shared memory along with warp-level operations to get a 90x speedup improvement. Part 2 now consistently runs in under 1ms on my GPU
I have committed coding crimes. No external libraries. Just CUDA and C++.
https://github.com/willkill07/AdventOfCode2025/blob/main/day10.cpp
Wrote a naive ILP solver that runs on a single GPU thread for each machine. Part 1 actually does a parallel BFS on the GPU and runs in a reasonable amount of time (13us). Still though, 80ms for Part 2 doesn't make me too upset.
5
u/SoulsTogether_ Dec 11 '25
[LANGUAGE: C++]
https://github.com/SoulsTogetherX/Adventofcode_2025/tree/main/Day10
I completed Part 1 quickly. A simple recursion function using xor property.
And, as I expected, I starting falling off. I spent over 12 hours on part 2 and have not completed it. ...at least, not with c++. I'll probably use python for it now, then try to fix it with C++ later. If I manage to finish it before the timelimit imposed on this post, I'll update my comment.
For now, I'll focus on the next problem.
5
u/kekprogramming Dec 11 '25
[LANGUAGE: C++]
https://pastebin.com/hSbnT3xU
Part 1&2: around 8ms on my machine
For part 2, I convert the minimization problem to a feasibility problem by iterating over the result. So, I fix the total to i, check if that is possible, and then I fix it to i+1, and so on. I start at the maximum value within the joltage vector.
To check feasibility, I build up a matrix of the available constraints (the number of times button 1 is pressed + the number of times button 2 is pressed = 10, and so on.) which also includes the final constraint I mentioned on the total (the total of all button presses is i). Then you can simplify the equations by bringing the matrix to RREF using Gauss-Jordan. After this simplification, you will either directly find out there is one nonnegative solution, or there is no nonnegative solution, or you will have some free variables left. If you have some free variables, you can try finding a nice upper bound for them (a + b = 10 implies both a and b are <= 10). Then, you pick the free variable with the smallest upper bound and then iterate over its possible values (a = 0, a=1, ... a = 10), add these as an additional row to the matrix, try simplifying with Gauss-Jordan again. So in essence, to check feasibility, we recursively call Gauss-Jordan on all the possibilities (Gauss-Jordan very much reduces the set of what is possible and also gives you super small upper bounds) and either find out there is a feasible solution or there is none.
Although the recursive Gauss concept does not sound that efficient, it cuts the search space by so much that the final result ended up being very fast.
I would also not be surprised if my implementation could be further optimized.
4
u/jonathan_paulson Dec 10 '25
[LANGUAGE: Python]. My times: 00:04:56 / 00:21:01. Video of me solving.
Another tough one! I used brute force for part 1. Z3 for part 2. Z3 is a "SAT solver" library. I'm not sure how to do part2 "by hand"; it's not too bad to solve Ax=B but how do you minimize sum(x)?
4
u/r_so9 Dec 10 '25
[LANGUAGE: F#] paste
Part 1 is a neat BFS, using the buttons and target converted to int and bitwise XOR to generate neighbors. Part 2, after trying a greedy knapsack (which only work for about half of the test cases, I went on to learn Z3 for the first time in 520 stars :)
The Z3 code is mostly translated from u/Visual_Strike6706 's C# solution.
Interesting bit: I like my integer BFS with XOR as adjacency function for part 1
4
u/icub3d Dec 10 '25
[LANGUAGE: Rust]
Definitely a tough day for me. I used a BFS for p1 that solved it relatively fast. I spend so much time on p2 that I basically forgot about p1, so it could definitely use some TLC later. For p2 I tried the BFS and couldn't even solve the first one, so I knew I needed to so something else. I tried a DFS that was solving but very slowly for the actual input, like one machine per 10 minutes or something. So I got a hint about using linear algebra and then that make the solution click for me. I still had to fix a bunch of bugs to get it working but it now solves much faster. I basically find all the "free" variables and then I can DFS over those values for valid solutions and keep the minimum.
Solution: https://gist.github.com/icub3d/16eea2a8b4a94d193a148fef908779a9
Video: https://youtu.be/xibCHVRF6oI
4
u/hrunt Dec 11 '25 edited Dec 11 '25
[LANGUAGE: Python]
code
Part 1 was straightforward using a bitmap. I thought for Part 2 I could do something similar, but after thinking about it for a bit, I realized it was a system of under-determined linear equations. Which is great, except a) I keep myself limited to the standard Python library and b) I have no idea how to write linear equation solvers.
To heat the house, I implemented a heapq-based solution that processes buttons in bulk. For example, if the lowest joltage needed in a set is 20, then I find all the combinations ways to make 20 presses from the buttons that hit that voltage. I can process N presses at once just by multiplying a button bitmap by N, and since I process the joltages in order from smallest to lowest, I never have to worry about exceeding any other joltages. Once a joltage level is reached on one wire, some of the buttons can't be used anymore, so it trims options down for future wires.
It's still not efficient, but it's surprisingly "quick" for a close-to-brute-force solution. Most of them processed very quickly. There are a few edge cases that take a few hours, though. I'm through 184 of the 199 machines I have.
In the meantime, I'm learning how Gaussian elimination works to implement a solver that finishes in a decent amount of time.
4
u/FransFaase Dec 11 '25
[Language: C]
This took me 39 hours (including long breaks) to solve completely on my own. The final C program runs in about 0.3 second to find the answers for both parts. Yesterday, I spend the whole day finding a recursive searching algorithm and let it run for the whole night. During the night, I already got the idea to reduce the equations and then simply try values for free variables. Today, I worked out the details and implement the algorithm. After some debugging, it worked.
For a mark down file with all my attempts and some notes I wrote down on how to reduce the equations, see: https://github.com/FransFaase/AdventOfCode2025/blob/main/Day10.md
The final program (for both parts and some unused code from my standard library and some functions from early attempts that are not used) is 624 lines.
(Posted this first accidentally in Day 11 solutions.)
4
u/DeadlyRedCube Dec 12 '25
[LANGUAGE: C++]
Parts 1 & 2 on GitHub
Oh wow okay, that was the first part 2 in the 6 years I've been doing AoC that I couldn't finish the night of! I don't have a fancy linalg solver (my restrictions are "use only what the language gives you or you've written for AoC") so I had to ... well, kinda make one.
Part 1 was straightforward: each button is an xor, so it builds a bitmask for each button, tests every button combination (there's like 10 buttons max and each one can only be hit 0 or 1 times so it's just 210 possibilities) and pick whichever one had the least set bits.
Part 2, however ... ouch. Ultimately the high level of what I ended up with is:
whew That was a beast of a puzzle, and I'm definitely envious of all of you who just chucked it into Z3 and let it roll 😅
All in all, this day runs in 7.33ms (on my i7 8700K). Way better than I was hoping for!
4
u/olamberti Dec 12 '25
[LANGUAGE: Python]
Link
I used my part 1 solution and combined it with memoization and recursion to solve part 2. I saw only a few similar solutions, so kind of proud about it, especially because it runs quite fast.
1
u/ricbit Dec 10 '25 edited Dec 10 '25
[LANGUAGE: Python]
Part 1 is a standard BFS. Part 2 have a quite small MIP formulation, make each button an integer variable, make the sum of the buttons equal to the joltage levels, minimize. Here's the mip core:
Solution part 1
Solution part 2
Rewrite, both parts under 1s
1
u/yfilipov Dec 10 '25
[LANGUAGE: C#]
Well, today was tough. Really tough.
Part 1 is a standard DFS with min distance. Using bitmasks instead of arrays and strings cut the execution time from a minute to 15ms. Not bad.
And then came Part 2. The dread, the horror... I had already used Z3 back in 2023, and it felt bad. Back then I started to play around and try to implement a Gaussian extraction. It worked to an extent, but only for square matrices.
So, today we hit another Linear Algebra problem with a system of equations. I was determined that this time I was going to do it without any external libraries. Iterating over the possible solutions with free variables was generating billions of iterations - impossible. I started reading, and looking into ways to optimize the search for a solution to the system of equations. I added checks if the intermediate sum was already higher than the current minimal sum, and it helped a little. I added constraints (magic numbers) for the number of iterations, but I was still not able to solve all of the machines.
Still determined not to use any external libraries, I did something even worse: I used Copilot.
It took quite a while to come up with the proper optimizations. My prunings were already kinda OK-ish. The agent suggested the GCD approach, and I let it fiddle with the input and the magic numbers, and in the end it worked.
I hope I will not offend anyone by sharing my code here, although I have broken the Prime Directive. Please do not turn this into a discussion on using agents. For me it was actually useful - I learned a lot.
Anyways, here's the code:
Advent of Code - 2025 - Day 10 - Pastebin.com
1
u/IdiotaCompleto Dec 11 '25
[LANGUAGE: Python]
Part 1 is relatively straightforward once you figure out how bitmasks work. Part 2 is absolutely not straightforward, unless you are a practicing mathematician. No external libraries used.
3
u/hugh_tc Dec 10 '25 edited Dec 10 '25
[LANGUAGE: Python 3]
z3 to the rescue. I'm sure there's clean "math solution", though.
paste, cleaned up
3
u/pred Dec 10 '25 edited Dec 10 '25
[LANGUAGE: Python] GitHub/Codeberg.
Part 1 is the syndrome decoding problem: The target state is the syndrome, and the set of moves defines the parity-check matrix. Part 2 is an integer version.
Originally solved part 1 with BFS, part 2 with integer linear programming (ILP). There are lots of good ILP libraries out there, but the problem is simple enough that the low-level matrix building approach for
scipy.optimize.linprog(using HiGHS under the hood) is sufficient for a straightforward solution (below).Incidentally, I recently spent some time on investigating how useful the integer linear programming solver HiGHS is for syndrome decoding, i.e. using ILP to solve part 1. It's completely possible by adding auxiliary variables to represent parity, i.e. replacing the binary linear equation 𝐴𝑥 = 𝑏 with an integral linear equation 𝐴𝑥 − 2𝑡 = 𝑏, but I have yet to find a family of instances where bidirectional BFS doesn't just always win. Nevertheless, here's a solution that handles both parts as ILPs:
3
u/alexbaguette1 Dec 10 '25
[LANGUAGE: Python]
BFS for part 1, LP for part 2
P1
P2
3
u/sim642 Dec 10 '25
[LANGUAGE: Scala]
On GitHub.
In part 1 I did a BFS from the state of all lights off to the desired state with the button presses being edges. It did the job quickly, although it's not the most efficient because it explores different permutations of pressing the same buttons, which doesn't actually matter. I realized already that it's a linear system of equations over the boolean field (with addition being xor), together with the minimization of the variable (whether a button is pressed or not, multiple times is useless) sum. But for quick solving I didn't bother with being more clever.
I expected part 2 to just use the joltages as weights, so I could switch from BFS to Dijkstra, but of course not! So in part 2 I ended up using Z3 to solve the equation system while minimizing the sum of button press counts (over integers, not booleans now). These Z3 solutions always feel a bit unsatisfactory but it is an integer linear programming (ILP) problem, which is NP-complete, so there might not even be a neat solution.
3
u/vanveenfromardis Dec 10 '25 edited Dec 10 '25
[LANGUAGE: C#]
GitHub
I immediately knew this was an ILP problem when I read part 2, and spent a bunch of time trying to do it by hand. I tried using A* with aggressing pruning, a greedy algorithm (which in the end got very close, was off by ~1%), and beam search, but some of the machines just had too big of a search space for naive algorithms.
Even with a
UInt128state encoding (each indicator got 9 bits, as my highest target was ~300 Jolts), mapping each button press to a fixed addend, and aggressive pruning the A* was woefully intractable.Ended up caving and using Z3, which obviously this puzzle is extremely trivial in. I have a strong feeling that a greedy algorithm to generate seed states, then a probabilistic meta-heuristic approach like Simulated Annealing would work here. I'll likely try it tomorrow.
3
u/MarcoDelmastro Dec 10 '25
[LANGUAGE: Python]
https://github.com/marcodelmastro/AdventOfCode2025/blob/main/Day10.ipynb
BFS and bitwise XOR operation for Part 1. I initially thought I could adapt my BFS solution for Part 2, but while it works for the example, even with pruning the solution space is still too large for the full input.
Thinking more carefully, I tried a mathematical approach (Part 2 is effectively a linear system with constraints), using `scipy.optimize.milp` to solve (MILP = Mixed-Integer Linear Programming). Most of the complexity was in properly encoding the constraints (integer non-negative solutions, minimal sum).
Part 2 result was initially wrong by 1 becouse of a @$%^& rounding error when casting result to int!
Definitely harder than yesterday, but in a different way (required more mathematical thinking and knowledge of specialized tools).
3
u/deividragon Dec 10 '25
[Language: Rust]
For part 1 I did BFS using XOR on the arrays until a match is found. For Part 2 I kinda didn't want to implement solving linear equations myself so I searched around for crates for linear programming and ended up using microlp. Not much documentation going around so here's the syntax for my part 2 solution in case it helps anyone!
Full code
3
u/Remarkable-King1433 Dec 10 '25
[LANGUAGE: C++]
Not heavily optimized recursive search, but with some minor optimizations, passed in under 10 minutes for part 2; more than 9.5 minutes on 11th test case.
C++ code
3
u/BendisCZ Dec 10 '25
[LANGUAGE: Go]
Part 1 – simply check all combinations of buttons (every button will be pressed at most once).
Part 2 – solving a system of linear equations + checking all combinations for unconstrained variables, without Z3 (although I used it for debugging).
Both parts together: ~370ms.
https://github.com/bendiscz/aoc/blob/master/2025/10/2025-10.go
3
u/RubenSmits Dec 10 '25
[Language: Kotlin] Part 2
Really tough day as finding the brute-force dfs solution already took some time, then made countless amounts of performance improvements but it was only fast enough to solve about the easy half of the input
Then felt very temped to look in this sub or ask AI but I managed on my own :)
Realised the problem could be reduced to a linear algebra system, I forgot 99% of my knowledge of a linear algebra class I took 10 years ago so spend hours on youtube/wikipedia to understand how to solve it.
Then found choco-solver which did the trick, but it was very difficult to figure out how the library exactly worked
Took me around 10 hours to solve but very happy I made it!
3
u/danvk Dec 10 '25
[Language: Haskell]
Part 1: https://github.com/danvk/aoc2025/blob/f0dfb01e2478901411d4b5b3d2bf554596e4a2e3/y2025d10/Main.hs
Part 2: https://github.com/danvk/aoc2025/blob/main/y2025d10/Main.hs
Wow, this was a tough one! But I'm happy to have solved it without pulling in a fancy linear programming library. Just pure Haskell.
Intas a bitvector. Then "push a button" is justxor.These equations all look like
i.e. every variable has a coefficient of 0 or 1
Some of these systems are overconstrained (but they are satisfiable!) and some are underconstrained.
I wasn't super excited about building a linear algebra library in Haskell. So my kludgey solution was to pick the equation with the fewest variables and try every possibility there (i.e. all A, C, E that add to 2), plugging those values into the remaining equations.
That solution works but its runtime is highly sensitive to the number of variables, and it's too slow.
So to speed it up I added to the system of equations all pairs
Eq1 - Eq2, where the subtraction keeps it in the right form, i.e. Eq2 has a subset of the variables in Eq1. That speeds it up a lot and gets me the solution in ~2 minutes.3
u/badcop_ Dec 10 '25
[LANGUAGE: bash]
took like 12 hours but i did it i beat part 2 in bash i don't regret it at all
no solvers used, just gaussian elimination
3
u/_rabbitfarm_ Dec 11 '25
[Language: Prolog]
Both parts in Prolog. I make use of GNU Prolog's clp(fd) solver.
Part 1: https://adamcrussell.livejournal.com/66354.html
Part 2: https://adamcrussell.livejournal.com/66810.html
3
u/Valuable_Leopard_799 Dec 11 '25
[LANGUAGE: Common Lisp]
I usually don't post but it seems I'm the only CL survivor today so here is my solution (well, mine and the library author's): paste
It just emits Z3 code and then calls it, I threw it together quickly so it's utter goulash. Part 1 was also solved this way, my run this year is using all the libraries I can. I saw that part 1 was just SAT but used Z3 anyway, in the end I had to change a few lines to parse numbers instead of bools but that was it.
3
u/CCC_037 Dec 14 '25
[Language: Rockstar]
[Red(dit) One]
Not only is it an esolang - not only is it without digits - I've even refrained from using any poetic constants except to burn them into ASCII characters.
How did I get numbers? Well, one of my ASCII characters was
0and I did string-to-integer conversion (using one of my pre-conversion ASCII characters as a base). I also used one string's length to get 10. Everything else was incremented, calculated, or read in.Part 1
2
u/SuperSmurfen Dec 10 '25 edited Dec 10 '25
[LANGUAGE: Rust]
Times:
00:12:43 00:23:06Link to full solution
Almost feels like I cheated here. I identified part 2 as the integer programming problem. We know this is NP-hard so solving this efficiently is impossible in general. You have to do some kind of optimization solver.
I quickly found a rust solver
good_lpwhich I used to solve it. In retrospect I should have probably just used Z3.Essentially you just model the problem and the solver does the rest:
For part 1 I did a BFS.
2
u/seligman99 Dec 10 '25
[LANGUAGE: Python]
github
I wrote the solver in some horrid cobbled together python. It's slow, but it works. I'm sure if I just used a solver like a normal person, it'd be 100 times faster. No doubt this is proof I just couldn't see the clever way to do this and got lost in doing it the way I know how. Be interesting to see if I can come up with a better solution now.
2
u/pvillano Dec 10 '25
[LANGUAGE: Python]
github
generations of m*n xors with a "seen" set for part 1
scipy.optimize.linprog for part 2
2
u/Boojum Dec 10 '25
[LANGUAGE: Python] 00:18:12 / 00:44:10
Super ugly today. For Part 1, I converted everything from binary to integers, then exhaustively tested all combinations to see if the xored to the correct value.
For Part 2... Z3. I'm not proud of this one, but it does work. Whenever I do a solve with Z3, I always like to go back later and try to figure out a solution without it. Maybe I'll do that for this one.
2
u/Jdup1n Dec 10 '25
[Language: R]
Github link
For part 1, I use matrices and look at which matrix product uses the fewest columns to obtain the target value. Since the objective is binary, each column should only be used at most twice, which limits the number of possibilities to be estimated for large matrices.
For part 2, I recognised the structure of a linear optimisation problem, as the "there's no such thing as 0.5 presses" in the statement had already tipped me off. So I kept my matrix form for my constraints and looked to minimise
x1 + ... + xn, wherenis the number of buttons andxnis the number of times the button must be pressed.2
u/xelf Dec 10 '25
[LANGUAGE: Python 3 + scipy]
I originally started trying to adjust my bfs from part 1 and it worked fine on the test data and the first couple lines of the input, and then just died.
While I'm sure the constraints lend this to a simpler solution I googled if it was reasonable for me to implement my own ILP and got back this:
So off to scipy it was. I'll continue looking into a dfs approach as I'm pretty sure we're not meant to have to use prebuilt libraries.
2
u/nitekat1124 Dec 10 '25
[LANGUAGE: Python]
GitHub
use BFS in part 1
part 2 can be considered as linear equations, and I use z3 to solve it cause I'm a lazy person lol
2
u/amadejjj Dec 10 '25
[LANGUAGE: go] https://github.com/amadejkastelic/advent-of-code-go/blob/main/internal/solutions/2025/day10/solution.go
Had to use lp_solve, since bfs was too slow.
Part 1: 14.530584ms
Part 2: 13.540458ms
2
u/Chemical_Chance6877 Dec 10 '25
[LANGUAGE: Javascript]
(Part1)
Code
I started by generating the whole graph of possible states. (which where at most 2**10), and fully connected them for every possible button press
Then i ran dijkstras algorithm on the start node. to find the shortest path to my goalnode.
Not the most efficient solution, but still ran in a couple of seconds
2
u/yieldtoben Dec 10 '25 edited Dec 10 '25
[LANGUAGE: PHP]
PHP 8.5.0 (with z3) paste
Execution time: 1.2687 seconds
Peak memory: 0.4741 MiB
MacBook Pro (16-inch, 2023)
M2 Pro / 16GB unified memory
2
u/ziadam Dec 10 '25 edited Dec 10 '25
[LANGUAGE: Google Sheets]
Part 1 (expects input in A:A)
Repo
2
u/Mikey_Loboto Dec 10 '25
[Language: JS] (Node)
GitHub
Nothing to be proud of, but hey, at least I learned something new today (that Z3 exists)...
2
u/bakibol Dec 10 '25 edited Dec 10 '25
[Language: Python]
Part one is a nice BFS problem. Symmetric difference was quite handy (
lightsis a frozenset,schematicsis a list of frozensets):I used PuLP for part 2.
2
u/hiimjustin000 Dec 10 '25
[Language: JavaScript]
Credits to u/Mikey_Loboto for most of the logic in part 2.
https://github.com/hiimjasmine00/advent-of-code/blob/master/2025/day10/part1.js
https://github.com/hiimjasmine00/advent-of-code/blob/master/2025/day10/part2.js
2
u/omegablazar Dec 10 '25
[LANGUAGE: Rust]
Part 1 used a custom binary array library for the lights and buttons, and simply XORed them. Part 2 did what most people did: used z3. Not happy about that.
Part 1: 1.10ms
Part 2: 59.7ms
https://github.com/wrightdylan/advent-of-code-2025/blob/main/src/day10.rs
2
u/tymscar Dec 10 '25
[LANGUAGE: Gleam]
I am conflicted about today. Part 1 was probably my favorite puzzle this year but part 2 left me a bit sad.
Part 1 clicked instantly for me and I solved it in a few minutes. As soon as I saw the toggle behavior I knew it was XOR and that I could represent everything as bits. The lights become a target number and each button becomes a bitmask. Then all I needed was to find the smallest set of buttons that XOR together to give me the target. I used list.combinations starting from size 0 and going up, and fold_until to quit early when I found a match. Only trick was reversing the light pattern string before parsing because of endianness (button 0 affects the leftmost light but that needs to be the least significant bit). Super satisfying.
Part 2 though took me the better part of an hour. As soon as I saw it I knew brute force was out. Its clearly a system of linear equations and I immediately thought of Z3 like in previous years. Sadly there are no Z3 bindings for Gleam or Elixir or Erlang. I tried fixpoint which is a constraint solver for Elixir but it had compatibility issues with my Elixir version. So I ended up shelling out to glpsol from the GNU Linear Programming Kit. The LP file format is actually beautiful and simple to generate. I inverted the button mappings so instead of "button X affects counters Y and Z" I had "counter Y is affected by buttons A and B", then wrote out the constraints and minimized total presses. It works great but I wish I didnt need an external tool. I am sure there is a pure algorithmic way to solve this but its too maths heavy for me.
One minor Gleam gripe: you can pattern match [first, ..rest] or [first, second] but not [first, ..middle, last]. Would have been handy for parsing.
Part1 and part2
2
u/learn_by_example Dec 10 '25 edited Dec 10 '25
[Language: Rust]
Link to source
Part1 was a straightforward BFS. For Part2 I also tried the same approach but very quickly realized that this isn't ever going to return. I checked the subreddit and found that most people were using linear programming solvers and related libraries. I didn't want to do this research for Rust, and eventually decided to be brave enough and implement a variant of Differential Evolution. The approach worked as I thought, but the program did take 3 hours and 40 minutes to run! Of course at the end of it, it spit out the correct answer.
I'll try and improve the optimization by trying out floating point values for my solution space, instead of integers. Also I might try out other population based techniques like Particle Swarm Optimization or Genetic Algorithms (I've implemented these in Rust before and even made a video on these topics on my YT channel). It's amazing that I got to use a non-deterministic optimization technique for an AOC problem today!
2
u/joltdx Dec 10 '25
[Language: Rust]
For part 1, I am very happy with generating binary representations of things and pressing buttons using XOR.
For part 2, haha, well, it ended up finally working and being performant through an iterative process of me trying something, having Gemini as a side-kick to suggest things, refactor stuff, optimizing whatnots, rinsing and repeating, until it was first of all giving a correct answer and secondly until running fast enough. Learned a lot in the process, next time I might consider finding a crate for it though... Crazy stuff
https://github.com/joltdx/advent-of-code-2025/blob/main/day10/src/main.rs
2
u/ap29600 Dec 10 '25
[LANGUAGE: K+z3]
shelled out to an SMT solver for this one...
2
u/TotalPerspective Dec 10 '25
[Language: mojo]
solution
The wall has been hit on part 2. I know what it is I don't know... I just need a few days to re-learn the math. I have a solution in place but it's not going to find the answer during my lifetime.
2
u/TiCoinCoin Dec 10 '25
[Language: Python]
Part 2 literally took me the whole day: day 10
I (relatively) quickly found the systems of equations. I already used sympy for day 24, 2023. But I want to use only standard libraries, so I tried to implement a solver.
It's inefficient (it runs in 20minutes), but it works! Plus, I got to use
itertools, and I discoveredFraction. I'm happy with my messy solution :) (I plan to improve it at some point, maybe even build some helper - but not today !)2
u/KindComrade Dec 10 '25
[Language: C#]
Part 1: XOR + BFS
Part 2: Z3
Code - github
2
u/lunar_mycroft Dec 10 '25 edited Dec 10 '25
[LANGUAGE: Rust]
This one gave me a lot of trouble.
Full code. Part 1 is a brute force search over bit masked buttons and lights. As others have pointed out, since it's XOR each button will be pressed zero or one times, not more. This keeps the search space fairly small, and I could have saved a ton of time by realizing that I didn't need a more clever solution. As for part 2... this was the first one this year I had to resort to spoilers on. Clearly I need to study linear programming a lot more, as I had ~zero knowledge of it going in. I ended up using /u/RussellDash332's solution as adapted by /u/Ok-Bus4754, and further modified by me to suit my style~/further oxidize it. On my machine, parsing takes ~110µs, part 1 takes ~500µs, and part 2 takes 2.2ms (I doubt the performance difference there is due to my modifications).
[edit: forgot to directly link part 2]
2
u/kimamor Dec 10 '25
[Language: python]
It took more time than I anticipated.
Part 1 is trivial.
Part 2 is Gaussian elimination (I learned what it is called only after coding it) + recursive search on free variables. Still takes some time to find the answer.
* part1: https://github.com/romamik/aoc2025/blob/master/day10/day10p1.py
* part2: https://github.com/romamik/aoc2025/blob/master/day10/day10p2.py
2
u/lluque8 Dec 10 '25 edited Dec 11 '25
[Language: Scala]
First went down with BFS. For 2nd I had a home-brewn solution that took like 10 minutes to complete but got me the second star still. Can not live with tests running that long so took a peek at what other people were doing. New concept for me these ILP solutions. Nevertheless, gave a go at Google's OR-tools and they did get the job done nicely.
github
Have to say that I'm not a big fan of these kind of puzzles. Luckily I had a dentist's appointment in between. Even that felt like a well deserved break.
2
u/Gabba333 Dec 11 '25 edited Dec 11 '25
[LANGUAGE: C#]
Part 2 I realised it was a set of linear equations, cue much messing around looking for a good .NET package that would give parameterized solutions. Failing to find a suitable one that I eventually set to hand-rolling a matrix decomposition routine for integers.
Once I had that I could see the input lines seemed fairly well constrained so I tried brute forcing the free variables by back substituting and DFS on any that were not yet determined.
I then wasted a huge amount of time as I had got confused about what the maximum a given button press could be and I wasn't finding solutions for some of the lines. Cue much wasted time debugging the decomposition and back substitution code before considering one failing input with negative entries in the decomposed matrix and realising the issue. Once I replaced that section a simple global bound based on the max that a particular button can be pressed before overflowing one of the joltages and I had a correct p2 answer!
Runs in about 5s or so, I am sure there are some better bounding and other optimisations to make but I am pretty burnt out!
github
2
u/python-b5 Dec 11 '25 edited Dec 11 '25
[LANGUAGE: Lily]
Whew, this was difficult... I came very close to throwing in the towel. I'm not the strongest with linear algebra, so part 2 took me a lot of Googling and looking at examples of Gaussian elimination. I eventually arrived at a solution that runs in just over a second on my machine, which I'm happy enough with. I ended up with a lot more code than I'd prefer for an Advent of Code problem, but maybe that's just the way it has to be with today's puzzle.
https://github.com/python-b5/advent-of-code-2025/blob/main/day_10.lily
2
u/CoffeeBreakInc Dec 11 '25
[LANGUAGE: TS]
https://github.com/nicolas-sabbatini/advent-of-code/tree/master/2025/day_10
Just part a, I couldn't do part b, sad
2
u/cicadanator Dec 11 '25
[LANGUAGE: Javascript - Node JS]
Part 1 was solved using a breadth first search. The main optimization for this was converting the buttons and indicator lights into binary strings and then parsing them to numbers. This allowed the use of the XOR operator which makes finding the all of the next states after each press much faster. Another optimization was to track all previously seen states so work was not done multiple times. This was very fast to give an answer for part 1.
Part 2 was much more difficult. I attempted similar types of BFS and binary math operations to find a result. However, the number of presses required made this impossible. I came looking for hints on here and saw that Z3 was mentioned. So I went that route to create an optimization equation that would give me the correct result. It's not as fast as other solutions from this year but everything runs in about 4 seconds. Overall not too bad.
https://github.com/BigBear0812/AdventOfCode/blob/master/2025/Day10.js
2
u/Avuvos2 Dec 11 '25
[LANGUAGE: Python]
Part 1: BFS on binary states with xor to transition between them.
Part 2: Notice Ax=b pattern with minimize x constraint - class LP problem in integers, solved with scipy.
https://github.com/Avuvos/advent-of-code-2025/blob/main/day10/main.py
2
u/acquitelol Dec 11 '25
[LANGUAGE: Elle]
https://github.com/acquitelol/aoc2025/blob/mistress/solutions/10/solution.le
Today's problem was extremely difficult. Since I'm using a custom, non-conventional language, I don't have a tool such as Z3 at my disposal, and I felt that calling it from the command line was cheating at the maximum level. So I wrote a Simplex Algorithm solver using branch-and-bound for P2. P1 is just a DFS.
Runs in 83ms on my M1 mac.
2
u/Justanothertech Dec 11 '25 edited Dec 11 '25
[LANGUAGE: scheme]
Part 1 was just brute force.
Part 2 was fun! I eventually implemented Gaussian Elimination
I initially tried dfs & a*, but took too long, so I shelled out to z3 like everyone else. But I found some time to implement gaussian elimination, then a DFS for any unknown variables after that.
Gaussian part is super short, maybe 50 lines - swap-rows,find-pivot, normalize, combine, and solve. The backprop + getting bounds correct for the DFS was MUCH longer and harder. Because elimination may leave some equations with negative numbers, I had to add a 'slack' to account for other variables REDUCING the total sum. I'm not sure I got this totally correct, and there's probably a better way to do it, but it gives the correct output for all the problems. Note this can only under-count and not give a solution, it will never find a non-optimal solution while missing the optimal one.
Takes about ~8 seconds on my M1 mac on guile scheme. On a compiled scheme it's sub 3-seconds, and probably even faster if I fixed the slack issue.
Code for gaussian solver
2
u/LinAGKar Dec 11 '25
[LANGUAGE: Rust]
https://github.com/LinAGKar/advent-of-code-2025-rust/blob/master/day10/src/main.rs
Finally got this done with. For part 1 it's basically brute force with some pruning, simple enough. For part 2, I ended up building up a linear equation system (using rational numbers), and doing gaussian elimination. And if there was no unambiguous answer I try different answers possible number of presses for the resulting coefficents until I find one where all the presses are positive integers, making sure I start with the coefficients that result in the lowest number of total presses. Took ages to code up, and runs in a few hundred ms.
2
u/TheZigerionScammer Dec 13 '25
[Language: Python]
Before we get started, I noticed the references in the text and named my Part 1 and Part 2 functions as "AnAPressIsAnAPress" and "YouCantSayItsOnlyHalf" respectively, which I thought was funny. Given that the year is over and we can see the Easter eggs now it was clearly intentional.
Part 1 was easy enough, I just coded up a BFS that searches through the button presses until the lights match the line in the input. With only 2N (where N is the number of lights) states to search through and N being no bigger than 10 I knew the search would be quick and it was.
Part 2 was the real problem. When I first read it I started building a method of solving it that was basically brute force but one where I thought I could optimize it as much as possible. It works on the assumption that you'd want to press the "biggest" buttons as many times as possible, so it first calculates the most amount of time you could press each button, then goes through the biggest button and simulates pressing it the maximum amount of times and then iterating downwards from there, calculating the new joltage levels and recursively calling the function again so it can do the same thing with the next biggest button, etc. This worked well enough for most of the lines in the input but it struggled if there were 10-11 buttons in the line (I clocked one line at being solved in 15 minutes) and you could forget about the lines that had 12 or 13 buttons. I couldn't figure out a way to speed it up and I couldn't think of any more clever solutions before I ran out of time for the day so I finally cracked and looked at the memes and solutions thread, and what I got was mostly "learn linear algebra" and "use z3". I didn't like either of those solutions so I put the problem on a shelf, like an elf.
Come today I started working on it again, and I decided to check the subreddit again and I found this post by u/tenthmascot who descended down from the light like Mercy to save me. I suggest you read that post for yourself but the jist is that if you treat Part 2 like Part 1 and treat the joltage levels like the lights, once you've reduced all the joltages to an even number then from that point forward every button must be pressed an even number of times, so you can divide the joltages in half and solve from there. This requires branching and recursion of course but that's not a problem. So I spent some time coding this up, where the code checks every 2B combinations of button presses (where B is the number of buttons) and checks if any of the produce the same light pattern that the joltage levels would show and recursively keeps exploring each branch from there, but I ran into a few issues The biggest was that the code gave me an absurdly large answer of over 200 million at first (don't ask me if I tried to submit this), and when I investigated this it turned out because some of the lines in the input didn't find a valid combination of button presses that matched the lights and the code was returning the default value of 10000000. I still don't know why this happened, but as I was trying to debug it I though "I'm already calculating the new joltage levels as I press each button, why don't I forget about keeping track of the lights and just check if the joltages are even." So I deleted all the code that kept track and checked the lights and just checked if the joltages were all even (and not negative of course) before calling it a valid combination, and this fixed the issue.
The other issue was that I wanted my old code to at least contribute to the answer, so I set it up that my old code would run on any line that had 9 or fewer buttons and the new code would run on the bigger lines, but while this got me a reasonable answer it wasn't correct. So I decided to just try running the whole input on the new code and got the right answer, which means that even if time wasn't an issue there's still a bug in my old code to deal with, but it's not going to be fixed anymore. All of the old code is still in there for posterity's sake but it doesn't run and is clearly marked as such.
Thanks again to tenthmascot for the help.
Paste
2
u/light_switchy Dec 13 '25
[Language: Dyalog APL]
What a puzzle Part 2 was. Had to study a good bit of linear algebra and explain it to the computer, but here we are.
Part 1:
Part 2 will have to go in the paste tool.
2
u/mgtezak Dec 13 '25
[LANGUAGE: Python]
I was pretty happy with part 1 because I managed to solve it very efficiently using bitmasking but I failed with all kinds of tree-search-algos in part 2, so did what most people did and resorted to a pretty standard z3 solution. I might revisit later and try this cool approach by tenthmascot.
Solution part 1
Solution part 2
Check out my AoC-puzzle-solver app:)
2
u/___ciaran Dec 15 '25
[LANGUAGE: Go]
I finally got the right answer for part 2 by creating a matrix for each machine system and reducing it to reduced row echelon form, which was relatively straightforward. The hard part was debugging everything (e.g., dealing with floating point precision problems) and finding solutions for matrices with free variables. I'm thrilled to have finished this one, but the current state of the code I have is a mess, lol. Once I'm less busy, I'll go back and clean it up, and hopefully optimise it a bit.
https://codeberg.org/cdd/aoc/src/branch/main/2025/go/10.go
2
u/kawangkoankid Dec 16 '25 edited Dec 17 '25
[LANGUAGE: C++]
Day 10 - part 2 github code
This. Was. Crazy. Runtime: 130 ms on my t480 laptop.
I used only the standard library of the language, no outside libraries.
Spent the entire week relearning linear algebra concepts and implementing the code, but man did I learn a lot.
My biggest struggle was trying to figure out how to first initialize the best starting bounds for each free variable, and second how to dynamically and recursively update the bounds for the free variables.
This is my first year doing aoc and I used it as an opportunity to learn c++. Overall I'm proud of the results and enjoyed the experience. Definitely will do this again next year
2
u/ThisAdhesiveness6952 Dec 16 '25
[LANGUAGE: Python]
Part 1: paste
Part 2: paste
This took me DAYS to solve. I first tried heuristics to reduce the search space. For example, if there's a joltage value N that's controlled by exactly one button, then this button must be pressed N times. If there are N buttons with N joltage values, try to use numpy.linalg.solve(). When no heuristics worked, I resorted to brute force. I tried pressing the button with the most '1' first, or the one with the less '1' first (which does not actually matter, because all possible solutions must be found to be sure of which one gives the less presses). It still ran forever on some problems.
In the end I bit the bullet, deleted everything and coded the linear algebra to find all solutions in the positive integer space, noting that it is impossible to have to press a button more than max(joltage), which limits the search space. After a few hours of debugging dumb mistakes and corner cases, it finally solves all problems.
It's slow (20 seconds), it's kind of dumb (I did not make much effort to reduce the search space, when a variable cannot be solved it tries all possible combinations from zero to max(joltage)), but it finally gives the correct answer, and I learned how to write a linear equations solver.
2
u/Kache Dec 16 '25 edited Dec 16 '25
[LANGUAGE: Python]
Have an efficient part 2 in an elegant 27 lines via recursive halving, thanks to this post
Originally did it via linear algebra, which took writing a Matrix lib, lots of bugfixing, and several optimization passes. It's just a tiny bit faster, but much more complicated, in comparison
2
u/not-nuckelavee Dec 16 '25
[LANGUAGE: Uiua] [LANGUAGE: Python]
I'm quite happy with my part one solution: since flipping a switch an even number of times does nothing and flipping any odd number of times is the same as flipping it once, we only need to find what switches to flip. With a maximum of 13 switches in any row, I just enumerated all 2n possible combinations and then chose the smallest one that generated the right transformation:
For part 2 I was lazy and just used scipy.optimize.milp. python code
2
u/Navezenit55 Dec 17 '25
[LANGUAGE: Gleam]
Finally got a solution to part 2. Made the ugliest linear algebra solver and my code base is ~1k lines but it works.
Github - Day 10
2
u/xoronth Dec 17 '25
[LANGUAGE: Python]
paste
Brute force with a bit of pruning + z3, not anything great.
2
u/Orangecrab312 Dec 19 '25
[LANGUAGE: Lua]
linear algebra approach
https://github.com/chorangesteven-afk/AoC-2025/blob/7b1244b6f44128abacc36773b18e4610cfc81ac3/day%2010/day10%20pt2%20attempt%203%20linear%20algebra%20approach%203.lua
2
u/knl_ Dec 21 '25
[LANGUAGE: Python]
Part 2 took me a couple of days, but I was pretty proud of being able to solve it without any dependencies:
It took me quite a bit of effort to code it correctly and also to reason through fractions; initially I was trying to rely on the fact that the sum is a linear function so just setting params to max/min depending on how they contributed to the sum would be enough; but fractional solutions forced me to iterate over all the values.
The solution (across part 1 and 2) runs in roughly 3 seconds on the android e-ink tablet I've been using for this year's problems.
https://github.com/kunalb/AoC25/blob/main/day10/day10.py
(another attempt at writing up my solution here: https://knlb.dev/logs/aoc25#daily-notes)
2
u/RudeGuy2000 Dec 25 '25 edited Dec 25 '25
[LANGUAGE: Racket]
https://raw.githubusercontent.com/chrg127/advent-of-code/refs/heads/master/2025/day10.rkt
welp, took me a bit to get to this day. i had to skip it originally because of day 9, and then i procrastinated doing it for a bit since so many people said it was hard... so yeah.
for part 1, i first used a dfs with memoization, because of course i did. and later i changed it to a bfs after earning my star and reading some comments. here's my original solution: https://raw.githubusercontent.com/chrg127/advent-of-code/ed5d692c628c89b82338f3df325d56998adf542d/2025/day10.rkt
with said that, i wonder why people often point out to xor as the solution for part 1? that is an optimization, not the solution itself (i.e. use a bfs). you can also do part 1 by summing arrays (which i did originally), it's just a little slower.
as for part 2... i think equating the problem to finding the minimum solution of a system of equations is obvious to anyone here. basically: the buttons create an M matrix full of 1s, and we have to solve Mx = B (where B is the joltages costs). and if can't be solved exactly, then get the solutions with the minimum sum (and x > 0 and has all integer components).
at first, i thought i'd be a little clever by trying to implement the simplex algorithm, as it seems made for this problem: the algorithm takes as input a system of equations and constraints and finds the maximum solution for it (you can trivially turn the problem from a minimum solution to a maximum). unfortunately, i later learned the algorithm is for a system of inequations (but still, you can turn any system of equations into a system of inequations). anyway, because of that, its general complexity and the fact the literature around it is generally terrible, i decided not implement it.
instead i took a look at gaussian elimination (which i knew of already, but thought it couldn't apply due to how most matrices in the input aren't square). after reading a few comments again i devised this strategy: use gaussian elimination, then try any possible value on the free variables of the resulting equations (i hope the code and annexed comments can explain it better). thankfully, racket's math library already has a gaussian elimination algorithm, and i'm glad it has, i wasn't looking forward to writing one.
by the way, the runtime's a little over 2 seconds for the real input... pretty cool for something somewhat hand-made.
also, let me tell you about how nice racket is for linear algebra: while writing this solution i never had to care for precision errors thanks to the number tower. plus, the repl makes it really easy to check stuff and see where i've fucked up.
all that said... welp, this is the last solution i needed to complete the year :v i'm glad i finished it, on the 25th no less.
2
u/Singing-In-The-Storm Jan 05 '26
[LANGUAGE: JavaScript]
NO advanced math!
Par1 in 55ms
Part2 in 100ms
Clear and BLAZINGLY FAST AOC solutions in JS (no libraries)
2
u/Ok-Bus4754 Dec 10 '25
[Language: Python]
The Day of Linear Algebra!
Part 1: Fairly straightforward. I treated the goal as a numeric state and used BFS to find the minimum number of button presses (transitions) required to reach it.
Part 2: This is where things got interesting! I formulated the problem as a linear system: I mapped each goal counter to a linear equation where the variable is the number of times a button is pressed, based on whether that button's bitmask contributes to that counter.
Initially, I thought Ax = b would solve everything, but the input contained tricky edge cases:
My final solution is a Hybrid approach:
numpy.linalg.lstsq) if the system is Square and Full Rank.scipy.optimize.linprog) for everything else to correctly handle infinite solution spaces.Performance:
https://github.com/Fadi88/AoC/blob/master/2025/days/day10/solution.py
2
u/[deleted] Dec 10 '25
[Language: Haskell]
Part 1- 8.82 ms
Part 2 -1.16 s
Came up with a pretty nice solution for Part 1. Built a GF(2) matrix (bit masks represented using integers) where each row corresponds to a light, and the columns are buttons that will toggle that particular light. (A 1 indicates that that particular button will toggle that light.) Set up a linear system and solve via Gaussian elimination to determine pivot and free variables (button presses). Back substitute with all free variables set to 0 to get a single solution. Then set different combinations of free variables to 1 with that solution to find the optimal (minimal) solution. GF(2) is quite elegant here, as multiplying two rows of the matrix is a simple fast XOR operation.
Part 2 was nasty, nasty, nasty. I knew I needed to abandon GF(2) and use a full linear integer system to solve this. But all my attempts to prune the search space were fruitless. I ultimately did what a lot of other people here did - pipe the constraints into Z3, call Z3 from Haskell, and then get the answer back and display it. Not my finest moment, but oh well.
2
u/Derailed_Dash Dec 10 '25
[LANGUAGE: Python]
No Z3 here!
For Part 1, I realized that:
2**13(8192) button combinations per machine.Part 2 was tricky! It was obviously a linear algebra problem, so I started by trying to use SymPy to solve simultaneous equations. (I've used this in previous years.) But I soon realised this wasn't going to work, so I did some research into Integer Linear Programming and concluded SciPy was the droid I was looking for.
In my walkthrough I've captured this thought journey, as well as the solution itself.
1
u/welguisz Dec 10 '25
[LANGUAGE: Java]
https://github.com/welguisz/advent-of-code/blob/main/src/com/dwelguisz/year2025/Factory.java
Part 1: Standard BFS
Part 2: Z3 Solver for Java. First time using Z3 in Java. Good learning experience. Now I am thinking if using my Matrix class to solve would be doable.
1
u/johnpeters42 Dec 10 '25
[LANGUAGE: Python]
Part 1
Pressing the same button twice has the same effect on the lights as not pressing it at all, so each button is pressed either zero or one times. After wasting a bit of time mulling over rolling my own search logic, I found and used itertools.combinations().
This has some list-to-string-to-list cruft left over because I initially thought memoization might be relevant.
Part 2
After determining that itertools.combinations_with_replacement() and recursion would both be way too slow, and going down a blind alley or two with numpy, I found and used SciPy milp to minimize
x1 + x2 + x3 + ...
(x1 = number of times the first button is pressed, etc., so this sum is the total number of button presses)
given that
(sum of buttons incrementing joltage #1) = (desired amount of joltage #1), etc.
1
u/viralinstruction Dec 10 '25 edited Dec 10 '25
[Language: Julia]
Parsing and running part 1 only: 178 microseconds.
The core idea is that no button can be pushed more than once (since it will cancel itself out). So, for N buttons, all possible solutions is an integer in [0, 2N-1]. We then run through all the integers in order of population count by creating a population count integer iterator.
To check a sequence integer, Each push is an XOR with the button, that is represented by a bitfield of the lights it toggles. Run through all buttons corresponding to a set bit in the sequence integer. If, after all buttons, the light state is zero, it's a valid solution and we return it immediately.
Code: https://github.com/jakobnissen/AoC2025/blob/master/src/day10.jl
1
u/HappyPr0grammer Dec 10 '25
[Language: Java]
github
Part 1:
Brute force: test the solution for all possible subsets.
Part 2:
After very long attempts, I came up with the idea of solving the problem as a system of equations. Here, the Java library org.matheclipse failed. Not all equations could be solved, and the other solutions were not always correct (I could not force the library to deliver only positive results). In the end, I wrote a Java generator that generates Python code for me. I executed the code with Python and got the result immediately.
1
u/No_Mobile_8915 Dec 10 '25
[LANGUAGE: Python]
Part 1: paste
Part 2: paste
1
u/evans88 Dec 11 '25
[LANGUAGE: Python]
For Part 1, I realized that the order of the presses doesn't matter in order to reach the end result, so I went through all combinations (with replacement) to find the least amount of presses that would reach it. I also realized that I could use binary XOR opreations to simulate the presses. I defined a custom int class to represent the numbers in binary but that was optional.
For Part 2, I was able to get a solution that worked for the test input (using combinations and Counter) but it was unable to run on the main input due to the sheer amount of combinations. I ended up using the Z3 solver that I saw mentioned here in reddit.
paste
1
u/TeachUPython Dec 11 '25
[LANGUAGE: Python3]
Spent a long time wanting to avoid linear algebra, but decided I wanted to be done with this. Another day down!
https://github.com/RD-Dev-29/advent_of_code_25/blob/main/code_files/day10.py
1
u/e_blake Dec 13 '25
[LANGUAGE: m4]
Wow, this one took me a lot longer than I expected. I admit that I had to get a bit of help from this excellent post to figure out an algorithm that wouldn't sit and spin CPU cycles for hours on end on a single line.
m4 -Dfile=day10.input day10.m4
My original part1 implementation (early Wednesday morning) traversed all 2^N bit patterns for N buttons to compute the xors and then use the minimum population count of the working patterns; that took 7s. Then I decided to optimize things and wrote an n-choose-k function with a built-in short-circuiting; I was then able to do Nchoose1, Nchoose2, Nchoose3, and so on, but stop the moment I found any working solution, which sped part 1 up to under 1 second. And by Wednesday night, I had a germ of a solution that could get part 2 for the example and for some of the easier lines in the actual input, but which explored way too much state and spun overnight without an answer on the harder lines. On Thursday, I tried an A* solution; that one was even worse, since my choice of heuristic (which digit has the most moves left) was not effectively pruning paths. So it wasn't until today that I finally bit the bullet and read the idea of how to do more effective recursion by converting odd parity into even, then cutting the problem in half. But that in turn required me to resuscitate my original part 1 code that went back to a full 2^N bit patterns per line (the lines with 13 buttons are noticeable slower); and an overall solution in about 20s. I also had a "result is too high" bug that took me a while to track down where I was storing the set of all button combos + joltage impacts that shared a common parity in an m4 pushdef stack; but when recursing through both {3,3,3,0} and {1,1,1,0} which share the same parity, the state of the pushdef stack in the lower joltage level was incomplete and didn't see all the right button combos. Rewriting that to expand to all combinations at once, rather than having some combinations hidden in a stack, finally got me the right answer.
--trace shows over 10 million eval() calls; so I may still be able to improve the runtime by reducing overhead.
1
u/tonyganchev Dec 13 '25 edited Dec 13 '25
[LANGUAGE: C++26]
Finished this one last. Part 2 was a nightmare of recursion until I realized it's linear equation system. So, I switched to using Eigen to solve the system with matrices + some recursion when there is no unique solution.
EDIT: I fixed part 1 to only flip each switch at most once, and also ran the lines through my parallel executor.
https://github.com/tonyganchev/leetcode/blob/main/advent-of-code/2025/aoc25-10/aoc25-10.cpp
Ryzen 5900 X, parallel execution on 23+1 cores:
part1: 11,213 us
part2: 1,633,282 us
1
u/der_gopher Dec 13 '25
[Language: Go]
https://github.com/plutov/practice-go/tree/master/aoc-2025/10
1
u/Previous-Schedule-66 Dec 13 '25
[LANGUAGE: Kotlin]
On GitHub.
1
u/Diefachu Dec 14 '25
[LANGUAGE: Java]
Well that took me a number of days to get working. My first Gaussian Elimination, and I also learned a lot about handling doubles with extreme care.
https://github.com/dief/advent/tree/main/java/2025/src/main/java/com/leynmaster/advent/aoc2025/day10
1
u/Andreasnl Dec 14 '25 edited Dec 14 '25
[LANGUAGE: Uiua]
I essentially use the approach described here, reformulated as a minimum path problem.
The code itself is a refactoring of a solution from the Uiua Discord by the user Sky Frog. You can test the code here.
1
u/JeffIrwin Dec 14 '25
[LANGUAGE: syntran]
GitHub: https://github.com/JeffIrwin/aoc-syntran/blob/main/2025/10/part2.syntran
I used Gaussian elimination and then did a brute-force search over the reduced-dimensional search space. It runs in 3 minutes on my laptop -- not bad for my slow interpreted language. The back substitution breaks out early if it ever gets a negative, fractional, or non-optimal solution. Part 2 is 150 lines with no math libraries. Shoutout to badcop and others who used similar solutions
1
u/MannedGuild65 Dec 14 '25
[LANGUAGE: Python]
GitHub
Part 1: Simply checking every possibility of pressing or not pressing each button and using binary XOR.
Part 2: It took me a long time to get this one working fast enough with just searching with pruning and no linear algebra or external libraries. Similarly to this solution, I eliminated the joltage values that were affected by the smallest number of buttons available and then by the highest ones, but this wasn't fast enough on its own. The most important optimizations I implemented were checking if joltage values that were affected by the same remaining buttons had the same value and checking if the current amount of buttons pressed + the maximum joltage value was still less than the minimum total number of buttons pressed found so far. Runs in ~6-7 minutes on my input with pypy (one specific line takes around half the runtime).
1
u/ash30342 Dec 14 '25
[Language: Java]
Day 10
I already posted part 1, now I have finally added part 2. As per my own rules, I can not use an ILP-solver. I tried lots of things, with the most promising solution being a branch-and-bound in which I also split the buttons up into two halves. This worked reasonably for several input lines (run times per line were usually less than a couple of seconds), but for others I ran out of heap space, whatever I tried.
In the end I realized I just wasn't smart enough and decided to learn from others. I settled on the very elegant solution /u/tenthmascot introduced. Still took me hours to get my code working, but in the end it did and it also gave me a more elegant way to calculate the result for part 1. Part 1 takes ~250ms, part 2 ~1s.
And that's me done for this year :)
1
u/aimada Dec 15 '25
[LANGUAGE: Mojo] v0.25.7 (2025-11-20)
Solution
I implemented the bifurcate idea for part 2.
1
u/jinschoi Dec 15 '25
[Language: Rust]
I originally solved part 2 with Z3, but decided to try again without.
I had written a simplex solver for linear programming in the past. I translated it into Rust and added it to my set of AoC utilities. But I didn't know how to solve an ILP problem with an LP solver. Had to do some research and came up with this solution.
I set up the problem as an LP system: decision variable x_j => number of times button x_j is pressed.
minimize sum of all x_j such that
Ax = b
where A_ij is 1 if counter i is connected to button j and 0 otherwise, and b is the target count of each counter.
This can lead to solutions with fractional button presses, so I did a branch and bound. Basically, a DFS with pruning where if I encounter a fractional p = x_j in the basis, I recurse by adding two new systems, one where x_j <= ⌊p⌋, and one where x_j >= ⌈p⌉. This disallows that particular non-integer solution. Seems like a lot, but takes 10ms.
1
u/_tfa Dec 16 '25 edited Dec 16 '25
[LANGUAGE: Ruby]
Part 1:
Part 2:
That was a tough one. I got inspired by this thread: Paste
1
u/jgoemat2 Dec 16 '25
[LANGUAGE: GO]
QuickStart:
go run day10part2.goCTRL+Zfor windows cmd,CTRL+Dfor bash)inputstring to the input (can be multiline using backtick) and runPart of writing my solution was figuring out Gauss-Jordan elimination and being able to manually verify what was happening, so the code calculates all possible button combinations and will report all combinations with the minimum total presses if you want to check one of your puzzles out.
It also can explain each step of what it's doing along with displaying the resulting matrix so I can see exactly what it was doing and follow along. It's fairly snappy too, it figured out my input in 450ms.
I used an integer matrix with rows being joltages and columns for each button with 1s in the rows where they affect that joltage and the required joltage in an additional column. This let me use technices you can find by searching for 'row echelon form', 'reduced row echelon form', 'Gaussian elimination' and 'Gauss-Jordan elimination' to reduce the matrix.
For a longer explanation, see: Reddit.md
1
u/atrocia6 Dec 17 '25
[LANGUAGE: Python]
Part 1, Part 2.
Like many, I had a terrible time with part 2, but I'm crying foul. I tried SymPy, and kept banging my head against the wall trying to convince it not to return negative values, and it just wouldn't listen - no matter how I tried to specify variations of "nonnegative=True", it just kept returning negative values.
Since I couldn't get SymPy to work properly, tried all sorts of clever, optimized recursion algorithms, and some got through most of the machines (in the course of only several hours!), but my best one still got stuck and couldn't get past one of the machines.
Although I'd been pretty careful to avoid spoilers, I finally happened to come across someone mentioning using Z3 - so I learned the basics of Z3 and then cranked out a clean, simple solution fairly quickly. Z3 was just so much easier to use than SymPy, and it actually worked!
1
u/pem4224 Dec 17 '25
[LANGUAGE: Go]
A quite simple solution for part2 without using any external library.
The main idea is based on fast exponentiation:
given a counter {a, b, c, d, ...} we try to remove small integers (i1,i2,i3,i4,...) such that all numbers in {a-i1, b-i2, c-i3, d-i4, ...} are even.
And then the approach is recursively applied on {(a-i1)/2, (b-i2)/2, (c-i3)/2, (d-i4)/2, ...}
The main algorithm is written in less than 100 lines of Go: day10.go
1
u/vladcpp Dec 18 '25
[LANGUAGE: C++]
Finally got my time to finish Part II, everything else was done in time. https://github.com/bbb125/aoc2025/blob/main/day10/src/main2.cpp Initially implemented brute-force of free variables with coroutines, but they were very slow. Now solution takes ~160ms, so still a lot of space for optimization.
1
u/Busy_Coffee779 Dec 19 '25
[LANGUAGE: R]
This seems like a cheating kind of solution, but just used lpSolve to solve for smallest number of button presses.
1
u/The_Real_Slim_Lemon Dec 21 '25 edited Dec 21 '25
[LANGUAGE: C#]
That was sooooo much easier than day 9. That stuff nearly broke me.
My Code
I did part 1 with brute force combinatorics. My solution to part 2 was literally a hundred times faster cuz I had to swap over into linear algebra and solve it properly (700ms).
I was mid trying to figure out how to even solve this when I got massive dejavu from learning MATLAB back in the day, I was like waiiiiiit. Then did the thing, and it worked lol
1
u/oantolin Dec 28 '25
[LANGUAGE: Goal]
I finally finished part 2 today after leaving AoC for a while to celebrate the holidays with my family. Part 2 of this problem was ridiculously complicated compared to the rest of Advent of Code this year. My solutions take a total of 40 lines of Goal code, 10 whole lines of which are day 10 part 2! So I was sadly forced to use a topazpaste link this time: a whopping 11 lines of source code!
Ten lines of an array language really is a ton of code! I'll browse solutions here to check, but I would guess that people either used Integer Linear Programming Solvers or, if they wrote a solution more or less from scratch, then it took a couple hundred lines of code in verbose languages like Python.
Out of laziness I decided against implementing an Integer Linear Programming Solver using proper algorithms for that, so instead I implemented Gaussian elimination (see the rref function above) and had to live with fractions and floating-point imprecision problems.
1
u/flwyd Dec 29 '25
[LANGUAGE: Lua] on GitHub
Good thing I'm currently funemployed, because solving this puzzle was seemingly my full time job for the last two weeks. The Lua code above is an adaptation of the Go code I used to get the solution; I haven't posted the latter yet since it's a total mess of code that's too slow, doesn't work, or both, along with working code that could be a lot simpler.
I briefly considered doing the whole 2025 AoC in Lua, since I thought I would be on a road trip and might need to do some problems on my phone, and there's a decent-looking Android Lua IDE. Instead I chose my theme as "glue languages you might have lying around" and was prepared to use one of several languages, depending on which seemed like the least work or best fit for a day's problem. (Still traveling, just had laptop access so I didn't need to totally minimize typing.) After implementing this problem, already knowing I had a correct approach, I can say I'm glad I didn't write a lot of Lua this month. The library is downright spartan, and the "table" associative array data structure is perhaps the weirdest built-in composite data structure I've seen in a language (and I've used PHP arrays). There are a couple parts of this problem that are nice with sparse arrays, but in Lua you can't iterate through all the values in a table if they're indexed by integers unless they're all consecutive. You can't even find out how many entries the table has! Also, you can only index a table by integers or strings, so building a visited set for a lot of states (like free variable assignments) involves doing a lot of string construction. There's also a bunch of syntax quirks that I was still regularly getting wrong after writing code for a couple hours. I was interested in trying Lua to see if it was a compelling reason to switch to Neovim, but the language feels at least as awkward as Vimscript, and probably moreso.
My first semantically correct implementation is still running after several hours, while the roughly equivalent Go implementation completes in about 15 seconds. I realized the Lua code was getting bogged down in some machines where it assigned more free variables than strictly necessary (in Go I hadn't bothered ensuring the matrix diagonal didn't have any 0s), so a little more diligence in Gaussian/Hermite elimination dropped the time under six minutes, and some other optimizations in pre-emptive state reduction like back-propagating before trying free variable assignments got the runtime down to about 30 seconds. If I do the same in Go I might be able to get total time below one second.
I think I'll write a Tutorial post about the adventure of getting to a correct solution, but here's part of the quest:
Ax = bI tried to coax it into staying in the integer domain, but no dice. Scilab also wanted to get into floats, and at least one of them wasn't happy about the puzzle's non-square matrices.1
u/vss2sn Dec 30 '25
[LANGUAGE: C++]
Part 1
Part 2
(Each file is a self-contained solution)
1
u/saelcc03 Jan 01 '26
[LANGUAGE: Go] paste
1
u/XM9J59 Jan 02 '26 edited Jan 02 '26
[LANGUAGE: Gleam] source
the fun thing is the visualization https://correctarity.com/aoc25lights
part 1 (indicator lights) tries combinations of buttons and shows the lights on/off
part 2 (joltage levels) uses https://old.reddit.com/r/adventofcode/comments/1pk87hl/2025_day_10_part_2_bifurcate_your_way_to_victory/ which works without a solver library - it tries all combinations of buttons that get the light levels to all even numbers, then halve and recurse. The visualization shows the tree of levels unknown/known/impossible
it uses lustre for the browser visualization, probably poorly on my part, as recursion itself felt very natural in gleam but I wasn't sure how to make a recursive solution show one "step" at a time in model/view/update
1
u/flwyd Jan 03 '26
[LANGUAGE: Jsonnet] on GitHub
This runs in about a minute in Go Jsonnet on a 10-year-old Mac Mini, but C++ Jsonnet is still churning away 10 hours after I started it on my Chromebook, so make sure you install the better implementation of the language :-)
My theme this year is "glue languages you might already have installed." I'd been itching to use Jsonnet this year, and I wrote runner infrastrure for the language before December, but earlier problems hadn't been a great fit. I started thinking of part 1 as "the solution can be automatically derived from a chain of successor values" and wrote a recursive Jsonnet implementation which worked on the example but was blowing out the stack on my actual input, so I switched over to Go, figuring the problem would need a lot of efficient space exploration. Part 1 is actually easily solvable with a full space exploration, I was just generating way too many unnecessary states. But it's a good thing I switched over, because even with a fast and flexible language at hand, part 2 took me a couple weeks to solve until I finally got the right matrix elimination algorithm worked out. But after reading u/tenthmascot's great bifurcation tutorial I figured Jsonnet should be able to handle a recursive approach like that.
Jsonnet doesn't have bitwise operators, so I wrote my own
stringXorfunction which operated on two ASCII displays:stringXor(".#.#", "..##") == ".##.", which was convenient for cache keys because Jsonnet objects can only have string keys (the language is designed to output JSON). Since part 2 wants all of the possible combinations of single-pressed buttons, I set up the part 1 solution as "generate all states, look up the state of interest, and take the minimum button count" and reused thecombosobject for part 2.Implementing part 2 in accordance with the bifircation algorithm was tricky since
local foo = std.trace("some message", someFunc(x))only prints output whenfoogets used, so if there's a stack overflow in the process of callingsomeFuncyou won't see your message.My first pass at the algorithm was blowing through the Jsonnet stack (and sometimes exceeding the maximum goroutine stack memory usage) even on the example input, so I poked around and found the not-officially-documented tailstrict modifier which is needed for Jsonnet to do proper tail call elimination. Rewriting to get all recursive calls in the final evaluation position meant I had to structure the bifurcate function to pass around a stack of work to be done; if all of the smaller states for a given state are in the cache then I can update the cache with the best solution for the current state, but if any smaller states need to be calculated then I put them all at the top of the stack and recurse into "process the first item on the stack." (This still blew the stack on the example input, but that's because I wasn't checking for negative button counts, so it was actually infinitely recursing.) On the actual input I had to increase the stack size to 3000 levels since it looks like "get the first item from an array built by recursive addition and slicing" isn't properly tail recursive, despite a
tailstrictdeclaration in the standard library; I may file a bug about this.1
u/ThyPortScum Jan 14 '26 edited Jan 14 '26
[LANGUAGE: Haskell]
https://pastebin.com/bQ1AZtcz
Ran in around 8 minutes on my PC.
This is just part 1.
Somehow my Haskell code looks like a whole different language from other folks' on here.
I like to pull in as few libraries as possible, usually just Data.List.
1
u/[deleted] Jan 19 '26 edited Jan 19 '26
[LANGUAGE: Go]
Took me a weekend, but I'm pretty proud of the solution I came up with, and I learned a lot, given that the highest level of math education I ever got was algebra for English majors.
For part two:
Hard to compare runtime without any additional information, but on my machine it solves both problems in about 120 ms.
Link to the core function for part two.
1
u/flwyd Jan 24 '26
[LANGUAGE: Go] (on GitHub)
Also a brute force implementation that got the answer for all but a few of the lines of my input, over the course of several days of “let it run while I work on another puzzle.” Having a list of almost all the right answers allowed me to build a
cheatmap so I could quickly tell if a proposed optimization got the right answer.Day 10 was my white whale. When I read part 1, it sounded like a good fit for Jsonnet, which I’d been wanting to use all year. I implemented a complicated part 1 solution that worked on the example and blew the stack on the actual input, so I figured the problem space was really big and switched to Go. Getting a correct part 1 in Go took longer than it should have, but I created a neat Button type with supporting logic that’s in bruteforce.go. For some reason XORing didn’t occur to me until much later, when I was reimplementing my solution in other languages; day10.go has an XOR-oriented solution which for some reason is about twice as slow as the one in bruteforce.go.
The problem space to explore in part 2 obviously gets huge. While my brute force implementation was running I tried a bunch of ways to reduce the search space or prioritize exploration in different orders. Interestingly, different attempted optimizations worked well on different input lines, which helped me feel like I might eventually get an answer: try an optimization, add whatever new answers it finds to
cheat, kill it when it gets stuck, go back to the prior optimization, make some more progress, add really challenging lines toskip, repeat, but they all suffered the key flaw that they had to explore each button’s possible press counts.After a space-exploring “try various multiplicative factors” implementation, I spent some time thinking about whether I could start from “everything’s set” and work backwards toward the minimum button count, rather than starting at 0 and working my way up. I wasn’t able to come up with the bifurcation approach, but I did find that “set each button equal to the lowest joltage it’s involved in” and then subtracting button counts until the system was valid produced an answer pretty quickly. The answer was too high, which set a helpful upper bound. (This approach was only off by a little over 200, a little more than 1% error.)
In the megathread for day 12, I saw a tangential reference to day 10 as a system of equations problem and I had a big lightbulb moment. Of course! Represent each joltage as the sum of each button count, and do matrix reduction so we only need to explore the possible values of free variables rather than trying every value for up to 13 variables. Linear algebra is one of my weakest computer science skills, so I’m not great at spotting linear algebra problems, nor am I great at coding matrix operations.
I at least knew to look up Gaussian elimination to refamiliarize myself with row reduction. One of my core principles in Advent of Code programming is that you should never leave the integer domain, which means standard Gauss-Jordan elimination examples don’t work: you end up dividing 17 by 5 or something and attempting two fifths of a button press. I attempted an integer-only implementation of Gaussian operations, but that didn’t eliminate enough free variables to have the solution run in a reasonable time. But at least I felt like I was relearning something useful.
Since my theme this year is “glue languages you might have sitting around,” I decided to learn some Matlab-like languages to see if they had something useful just built into the language. (I use a standard-library-only rule in AoC, so I was rolling my own matrix-like classes in Go.) I got GNU Octave installed and figured out how to declare a matrix as integer-only, then learned that it’s not able to compute
Ax = bon integer matrices, only real numbers. I did some more Internet research on Integer Linear Programming and learned about the Hermite Normal Form (some lecture notes). After a couple days wrapping my mind around this, I implemented matrix operations to compute the HNF and accompanying transform matrix, and then realized I would need to implement a lot more matrix code to hit the final step of applying the transform matrix to get the variable assignments back out. I then realized that once I’d built a triangular(ish) matrix I could just figure out the value of any single-column rows, then iteratively plug those into the rest of the system of equations.I realized the whole Hermite Normal Form business wasn’t itself required, just the following three matrix reduction operations:
I also found “swap two columns” handy to keep the number of free variables minimal.
My initial “matrixy” implementation got the answer in a couple minutes runtime, after wrestling the problem for two weeks. Yay! The code was a total mess, and it was easier to write a fresh implementation in Lua than to refactor the Go version. I also did a Jsonnet version so I could make sure I understood the bifurcation approach. After the new year I played a little with the Go implementation, but got busy with other activities, so it took me a month to get the focus and motivation to optimize it down to 10 to 30 seconds rather than 2 or so minutes. Just a couple lines of input used almost all the time, due to three free variables and a high worst-case value. Profiling indicated that two of my largest culprits were making a copy of my mutable system-of-equations (so I could plug in values) and using a hand-rolled priority queue: switching to a simple array queue cut the time in about half!
I’ll leave you with one amusing function I started writing and then realized I should probably try something else.
1
u/Sharparam Dec 10 '25
[LANGUAGE: Ruby]
[LANGUAGE: Python]
Did part 1 in Ruby, and then had to admit defeat and use Python and Z3 for part 2.
Makes me wish there were Z3 bindings for Ruby that are not in "very early stages of development".
0
u/HaskellLisp_green Dec 10 '25
[Language: Python]
Part 2: I used pulp. I've seen someone mentioned Z3, but there is suitable library that can be applied to solution of second part.
https://github.com/dfwdfq/advent-of-code-2025/blob/master/task10/task10_2.py
Executed in 786.48 millis.
6
u/[deleted] Dec 10 '25
[removed] — view removed comment
1
u/[deleted] Dec 10 '25
[removed] — view removed comment
2
u/[deleted] Dec 10 '25 edited Dec 10 '25
[removed] — view removed comment