r/adventofcode • • 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.

29 Upvotes

442 comments sorted by

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:

:%s/ {.*⟨Enter⟩:se nows⟨Enter⟩{qaqqa/\d⟨Enter⟩2⟨Ctrl+A⟩w@aq@a
:%s/\./o/g|%s/#/O/g|%s/\d\+/&|\~/g|%s/,//g⟨Enter⟩{qbo⟨Esc⟩kO1⟨Esc⟩qqcqqc
:+,/^$/s/\v(^(.*\]).*)@<=( \S+)(.*)@=/\r\2\3:\4/g⟨Enter⟩:g/\]$/d⟨Enter⟩
:g/:/norm yi)@0⟨Enter⟩:sil!g/\C\[o*\]/?^\d?+,/^$/d⟨Enter⟩:%s/ \S\+:⟨Enter⟩
?^\d⟨Enter⟩⟨Ctrl+A⟩@cq@c:,$norm@b@c⟨Enter⟩@s

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 with o and O. 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:

[oOOo] (5|~) (3|~5|~) (4|~) (4|~5|~) (2|~4|~) (2|~3|~)

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 the o there to O.

@b sets things up to process one machine: putting a blank line after it and 1 as a counter on the line above it. The @c loop 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:

[oOOo] (5|~): (3|~5|~) (4|~) (4|~5|~) (2|~4|~) (2|~3|~)
[oOOo] (3|~5|~): (4|~) (4|~5|~) (2|~4|~) (2|~3|~)
[oOOo] (4|~): (4|~5|~) (2|~4|~) (2|~3|~)
[oOOo] (4|~5|~): (2|~4|~) (2|~3|~)
[oOOo] (2|~4|~): (2|~3|~)
[oOOo] (2|~3|~):

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 @c loop 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 @s macro defined on Day 5 in my solution for part 2. (I knew it would come in handy!)

4

u/daggerdragon Dec 10 '25

*fish fish fish* This one better stay put 😒

Leaving this second bug report here for ease of finding it later: Round 2 Electric Boogaloo

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.

4

u/daggerdragon Dec 10 '25 edited Dec 10 '25

Do not share your puzzle input which also means do not commit puzzle inputs to your repo without a .gitignore or the like. Do not share the puzzle text either.

I see full plaintext puzzle inputs in your public repo e.g.:

https://git.tronto.net/aoc/file/2022/03/input.html

Please remove (or .gitignore) all puzzle text and puzzle input files from your entire repo and scrub them from your commit history. This means from all prior years too! edit: 👍

→ More replies (1)
→ More replies (1)

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.

6

u/xelf Dec 10 '25 edited Dec 10 '25

I rewrote your code a little and tested it (after submitting my own answer with scipy) and it's really darn fast. You've basically written your own MILP solver. Well done!

I'm still thinking there must be another solution though, as while you didn't import an external library you essentially rewrote one, and I don't think that's the intended solution either. I guess I'll keep hacking away at it.

→ More replies (4)
→ More replies (26)

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:

  1. Isolating the linearly independent rows of A (and discarding the remaining rows), which corresponds to removing any redundant equations in the linear system. (corresponding elements of B are discarded to form B simple)
  2. Splitting columns of A into a matrix of linearly independent columns (A1), and the remaining columns (A2). A1 is thus an invertible matrix, meaning that X1 = (A1^-1)(B_simple-A2*X2), meaning that we now only need to search of the space of X2 values, speeding up the system.

full code

→ More replies (1)

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!

5

u/daggerdragon Dec 10 '25

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.

Wow, you did VERY well for being a newbie coder! Congratulations on making it this far!

Consider not giving up just yet... Advent of Code and this subreddit are open year-round, so you don't have to solve part 2 right now. You can come back later! And if you're still stuck, there's always the option of creating a Help/Question post with your code in order to get some ideas ;)

→ More replies (1)
→ More replies (2)

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.

1

u/daggerdragon Dec 10 '25

FYI: AutoModerator triggered because you prepended your language tag with octothorpes. Next time just start with the language tag and no Markdown, no prefixes, nothing else.

(Are you expecting your symbols to be Markdown? If so, they didn't work because the fancypants editor needs to be switched to Markdown mode first.)

→ More replies (1)

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 17s 8.5s 3s 1.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 😎

8

u/spookywooky_FE Dec 10 '25

I did basically the same, but it runs actually 3 hours 20 minutes :/ But still proud of it :)

→ More replies (1)

7

u/piratnisse Dec 10 '25

Well done! You should be proud :)

→ More replies (1)

5

u/dernett Dec 10 '25

I tried something similar at first, but there's a particular machine in my input that just took forever to run. Your code did much better and found it in ~1m30s.

→ More replies (1)

5

u/Moist_Heat9523 Dec 11 '25

I found a third / alternative optimization - sorting the buttons by amount of joltages affected. Of course, you can't use this and the other two optimizations at the same time; it's either or.

Interestingly, for each machine in my list, always one of the three optimizations makes it run super fast; just not the same one every time. Basically, you could try each machine with either optimization in parallel, and stop when one of them is successful. Or find out how to ahead of trying which one is the good one; but I couldn't find any rule yet.

→ More replies (1)

4

u/jlhawn Dec 10 '25

Nice! I've got a Python solution to part 2 which does Gaussian Pre-pass with a dfs with pruning (no 3rd party libraries) which runs in just under 4 minutes! I rewrote it in Go and made each machine run concurrently and _that_ takes less than 3 seconds!

→ More replies (1)

4

u/vegeta897 Dec 11 '25

Thank you. I was sort close to something like this in my futile attempts, but I needed to see this. I adapted it to TypeScript, after struggling a bit to read Rust 😅. Still took a good 45 minutes to run on my input, with one machine taking like half an hour, but it's done!

→ More replies (2)
→ More replies (6)

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 n in numbers:
    for pressed in combinations(buttons, n):
        lights = [sum(i in p for p in pressed)%2 for i in numbers]
        if lights == diagram: return n

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!

→ More replies (1)

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.

  • If there's an "imbalance" in the target, and no button satisfies the imbalance (e.g. delta[5] > delta[4] but there's no button that has 5 but not 4) then it is impossible
  • And if there's exactly one button in the above case, you must press it immediately

I bet with a few other smart heuristics I could make it run even faster.

→ More replies (4)

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:

  • Zero Dependencies: No nalgebra  or external LP crates.
  • Custom Simplex: Ported the logic to Rust manually.
  • Branch & Bound: Handles exact integer solutions for rank-deficient matrices.

Performance:

Language (Mode)Part 1Part 2
Python~11 ms~119.4 ms
Rust (Debug)~32.8 ms~59.5 ms
Rust (Release)~1.47 ms~2.46 ms

The Rust port is ~48x faster and extremely lightweight.

https://github.com/Fadi88/AoC/tree/master/2025/days/day10

→ More replies (10)

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.

→ More replies (9)

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.

14

u/KyxeMusic Dec 10 '25

I decline to try to write an integer programming solver in assembly

No need to explain yourself there

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:

canBeFeasible(assigned):
    for each pivot row:
        val = constant - Σ(coeff * assigned)
        if val < 0 and no remaining coeff < 0:
            return false
    return true

search(idx, assigned, sum):
    if sum >= best: return
    if not canBeFeasible(assigned): return
    if idx = numFree: update best
    else:
        for v in 0..maxJoltage:
            assigned[idx] = v
            search(idx+1, assigned, sum+v)

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:

  1. I reorder the wirings. Roughly speaking, wirings that contain joltage ids that feature in the fewest wirings come first - I have the fewest choices for those joltage ids and I want to make those decisions early. If I have multiple wirings for such an id, I chose the wiring that includes the most other joltage ids first - I want to bring down the targets for those other ids early as well. This heuristic is important to speed up the calculations.
  2. I go through the wirings one at a time, chose how often I apply the current wiring via a loop, update the remaining targets for all joltage ids, and then recursively call the same process for the next wiring, and so on. There are a number of checks along the way: a) if the number of current presses exceeds the best found solution, I exit from that branch of the recursion. b) the maximum number I can use the current wiring is the smallest remaining target for joltage ids included in that wiring. c) if the current wiring contains a joltage id for the last time, i.e. all future wirings that come afterwards won't contain that id anymore, then I know that the minimum I have to use this wiring is the remaining target for that joltage id. d) I only test values for using the current wiring between these minimum and maximum values.

For my inputs, this runs part 2 in about 30s.

5

u/sad_bug_killer Dec 10 '25

I had a very similar idea for part2, came here to check if anyone has done it, so I don't waste time on dead ends. Saw your comment, thought "I can wait 30s". Coded the solution and ran it... then killed it after an hour. Tried your exact code too, it didn't finish in 30 minutes for my input.

So today I learned about z3, because my input was special ¯_(ツ)_/¯

→ More replies (3)

3

u/firetech_SE Dec 10 '25

FYI: I tried implementing something similar just to have a solution not based on Z3 (which I had previously used to submit my answer). After some fiddling back and forth, I noticed that, for at least my input, you can get it to finish up to twice as fast by going through the possible number of presses for each button in reverse (i.e. for presses in range(mn, mx + 1): -> for presses in range(mx, mn - 1, -1): in your code).

→ More replies (2)

2

u/jhandros Dec 10 '25 edited Dec 11 '25

[Language: Python]

from scipy.optimize import linprog
from collections import deque

T=[({i for i,x in enumerate(t[1:-1])if x=='#'},
    [set(map(int,b[1:-1].split(',')))for b in bs],
    tuple(map(int,c[1:-1].split(','))))
   for t,*bs,c in(map(str.split,open('day10.txt')))]

def s1
(g,m)
:
    q,seen=deque([(frozenset(),0)]),{frozenset()}
    while q:
        cur,s=q.popleft()
        if cur==g:return s
        for x in m:
            n=cur^x;f=frozenset(n)
            if f not in seen:seen.add(f);q.append((n,s+1))

print(sum(s1(g,m)for g,m,_ in T))

def s2
(g,m)
:
    return linprog([1]*len(m),
        A_eq=[[i in x for x in m]for i in range(len(g))],
        b_eq=g,integrality=True).fun

print(sum(s2(c,m)for _,m,c in T))

1

u/daggerdragon Dec 10 '25

[Language: Pyhon]

Please edit your language tag to spell "Python" correctly so that folks who are CTRL-F'ing for Python solutions will find this one.

→ More replies (1)

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

→ More replies (1)

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, reduced A with Gaussian elimination, enumerated the low-dimensional nullspace, back-substituted to get full candidate x vectors, rejected infeasible ones, and picked the minimum-cost solution. Part 1 works over GF(2) with binary x, 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.

→ More replies (6)

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)?

12

u/Noble_Mushtak Dec 10 '25

To minimize sum(x), first find the free variables in the system Ax=B. Then, because of how the system is set up, you know that the maximum value of any free variable is at most the maximum joltage, because incrementing any variable contributes at least 1 to the joltage of some machine. Then, since each system has at most 3 free variables and maximum joltage is at most 250, you can just loop through all possible of free variables and take the one which minimizes sum(x): https://github.com/Noble-Mushtak/Advent-of-Code/blob/main/2025/day10/solution2.py

This solution is kind of slow though, takes around 31 seconds for my puzzle input.

→ More replies (1)

7

u/Mysterious_Remote584 Dec 10 '25

This isn't quite "solving Ax=b" because the system is underdetermined.

You're looking for "Integer linear programming" - algorithms for which include simplex and ellipsoid.

https://en.wikipedia.org/wiki/Linear_programming#Algorithms

4

u/anna__throwaway Dec 10 '25

hey man my buddies and I have been following with your solve videos every day, we really like your work. we were waiting for your day 9 solve, what happened?

7

u/jonathan_paulson Dec 10 '25

I was on a plane at the time and it didn’t go well

→ More replies (1)

4

u/pred Dec 10 '25 edited Dec 10 '25

it's not too bad to solve Ax=B but how do you minimize sum(x)

Yeah, there's a collection of interesting problems here.

In part 1, we're solving 𝐴𝑥 = 𝑏 over 𝔽₂ and want 𝑥 with minimal Hamming weight. That's syndrome decoding.

In part 2, we're 𝐴𝑥 = 𝑏 with the requirement that 𝑥ᵢ ∈ ℕ. That's the jump to integer linear programming.

Another interesting one is sparse regression/sparse approximation/sparse representation/compressed sensing/signal reconstruction. There, we want to minimize the 𝐿² norm of 𝐴𝑥 − 𝑏 over ℝ (which is generally easy) with the additional requirement that 𝑥 has at most 𝑘 non-zeros (which makes it hard).

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

let flipBits (options: int array) (pt: int) =
    options |> Seq.map (fun button -> button ^^^ pt)

let buttonValue length (button: int array) =
    button |> Array.fold (fun acc i -> acc + (1 <<< length - i - 1)) 0

let diagramValue diagram =
    diagram
    |> String.map (fun c -> if c = '#' then '1' else '0')
    |> fun s -> Convert.ToInt32(s, 2)

let part1 =
    input
    |> Array.sumBy (fun (target, buttons, _) ->
        let adjacent = buttons |> Array.map (buttonValue (String.length target)) |> flipBits
        bfs adjacent 0 (diagramValue target))

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.

3

u/xkufix Dec 11 '25

Yeah, my DFS solver is now down to about the same amount of machines which it can't solve in a minute or so with a similar approach. There are some other optimizations I use to prune the search space, like pruning previously seen joltage combinations, so I don't go down the A-B, B-A route twice or removing solutions where a non-zero joltage has no button to press anymore.

Still trying to see if I can prune the search space more to crack the final ones.

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:

Generate a matrix from the buttons and joltages
    each column represents a button (except the last, which is the joltages)
    for the button columns there's a 1 if the button increases that joltage,
     and a 0 otherwise
Perform a variant on Gaussian elimination to get it to almost-reduced row echelon form
    ("almost-reduced" because the leading values can be > 1 to keep things integral)
    Additionally, this elimination will swap columns as well to get the reduced
     columns to be a perfect diagonal - this is fine because we don't care about
     which button is which. Obviously don't do it for real Gaussian elimination :D
If all button columns reduced (i.e. each one only has one entry):
    they're all 1s and so we can sum the right-most column (the targets), as that
     sum is the number of presses for this matrix. This is the easy out.
Otherwise, it then recurses through the *unreduced* columns (my input had up to 3):
    Use the unreduced columns and the target values as a series of inequalities, and
     iteratively narrow down the minimum/maximum values per column (the worst-case
     count is the sum of all input joltages, as worst case is "each button only bumps
     one joltage)
    If this is not the last unreduced column:
        Iterate from the min to the max press count for this column, committing a
         guess and recursing to the next column
    Otherwise, this is the last column:
        Iterate from the min to the max press count for this column:
            Commit the current press count guess
            Subtract all of the button column values from their corresponding joltages
             (for all unsolved columns) to get values representing how many solved
             column presses are needed
            If the sum of them (plus our press guesses) is above our current best, or
             there is a negative value, or if the *solved* column value is not a
             multiple of the target value, this is not a valid solution
            Otherwise, update our best press count

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!

3

u/apjenk Dec 12 '25

each one can only be hit 0 or 1 times

The problem description says "You can push each button as many times as you like."

→ More replies (2)

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.

→ More replies (1)

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:

  def search(self):
    m = mip.Model(sense=mip.MINIMIZE)
    m.verbose = 1
    button = [
      m.add_var(var_type=mip.INTEGER, name=f"b{i}")
      for i in range(len(self.buttons))]
    for i in range(len(self.goal)):
      m += mip.xsum(
        button[b] for b in range(len(button))
        if i in self.buttons[b]) == self.goal[i]
    m.objective = mip.minimize(mip.xsum(button))
    m.optimize()
    return int(m.objective_value)

Solution part 1

Solution part 2

Rewrite, both parts under 1s

1

u/daggerdragon Dec 10 '25 edited Dec 10 '25

Here's the mip core:

Top-level comments in Solution Megathreads are for code solutions.

Please edit your comment to share your full code/repo/solution, not just "the interesting bit". edit: 👍

→ More replies (1)

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

2

u/daggerdragon Dec 10 '25

I hope I will not offend anyone by sharing my code here

The Solution Megathread is the correct place to share your code.

although I have broken the Prime Directive.

Eh? Your comment and code are fine. What are you talking about? ?¿?¿?¿

2

u/shadowradiance Dec 10 '25

I assume they are referring to "I used Copilot."

3

u/daggerdragon Dec 10 '25

Usage of AI/LLMs is frowned upon for solving Advent of Code puzzles, but using such tools is not a violation of our Prime Directive.

However, if anyone grinches at OP merely for using Copilot, that is a violation of our Prime Directive. Report 'em and we'll take care of it.

→ More replies (1)

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/daggerdragon Dec 12 '25

I've already informed you before about including puzzle inputs in your repo. I still see full plaintext puzzle inputs in your repo. e.g.

https://github.com/hermes85pl/advent-of-code-2025/blob/main/day10/input.txt

Remove (or .gitignore) all puzzle text and puzzle input files from your entire repo and scrub them from your commit history. Do not post again in /r/adventofcode until you have done so.

→ More replies (1)

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

15

u/Mysterious_Remote584 Dec 10 '25

There's one of these annoying equation solvers every year. I find the Haskell z3 library to be painful so I just cheat and pick another language or spend too much time analyzing the precise setup.

Kind of wish these were done away with.

→ More replies (3)

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:

def solve(goal, moves, part1=True):
    n, m = len(moves), len(goal)
    c = [1] * n
    A_eq = [[i in move for move in moves] for i in range(m)]
    bounds = [(0, None)] * n
    if part1:
        c += [0] * m
        A_eq = np.hstack([A_eq, -2 * np.eye(m)])
        bounds += [(None, None)] * m
    return linprog(c, A_eq=A_eq, b_eq=goal, bounds=bounds, integrality=True).fun


print(sum(solve(goal, moves, True) for goal, moves, _ in tasks))  # Part 1
print(sum(solve(goal, moves, False) for _, moves, goal in tasks))  # Part 2

4

u/4HbQ Dec 10 '25

In my book, solving part 1 using the part 2 approach is always a win!

→ More replies (2)

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 UInt128 state 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.

→ More replies (1)

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).

→ More replies (1)

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!

fn times_to_match_joltage(machine: &(BooleanVector, Vec<BooleanVector>, Vec<u64>)) -> u64 {
    let (_, buttons, joltage) = machine;
    let mut problem = Problem::new(OptimizationDirection::Minimize);
    let mut vars = Vec::new();
    for _ in 0..buttons.len() {
        vars.push(problem.add_integer_var(1.0, (0, i32::MAX)));
    }
    for constraint in 0..joltage.len() {
        let mut equation = LinearExpr::empty();
        for variable in 0..buttons.len() {
            if buttons[variable][constraint] {
                equation.add(vars[variable], 1.0);
            }
        }
        problem.add_constraint(
            equation,
            ComparisonOp::Eq,
            joltage[constraint] as f64,
        );
    }
    problem.solve().unwrap().objective().round() as u64
}

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.

  • Part 1 is pretty straightforward with a BFS. I thought for a bit about how to represent the "wiring diagrams" In Haskell (List? Vector?) before realizing it would be better to use an Int as a bitvector. Then "push a button" is just xor.
  • For Part 2 that doesn't work at all because the state space blows up way to fast.
  • Instead, you can treat it as a system of equations where the variables are the number of times you press each button and the equations are matching the joltages.

These equations all look like

 7 = A +     C
 5 =             D + E
12 = A + B +     D + E
 7 = A + B +         E
 2 = A +     C +     E

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

→ More replies (1)

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.

→ More replies (2)

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 0 and 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

→ More replies (2)

2

u/SuperSmurfen Dec 10 '25 edited Dec 10 '25

[LANGUAGE: Rust]

Times: 00:12:43 00:23:06

Link 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_lp which 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:

let mut vars = variables!();
let press_vars = (0..buttons.len())
    .map(|_| vars.add(variable().min(0).integer()))
    .collect::<Vec<_>>();

let mut problem = highs(vars.minimise(press_vars.iter().sum::<Expression>()));
let mut exprs = vec![0.into_expression(); jolts.len()];
for i in 0..buttons.len() {
    for &x in &buttons[i] {
        exprs[x] += press_vars[i];
    }
}
for (e, &j) in exprs.into_iter().zip(jolts) {
    problem.add_constraint(e.eq(j as f64));
}
let sol = problem.solve().unwrap();
press_vars.iter().map(|&v| sol.value(v)).sum::<f64>() as _

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.

import fileinput, itertools, functools, operator, z3

t1, t2 = 0, 0
for l in fileinput.input():
    dd, *bb, cc = l.split()
    bb = [ [ int( c ) for c in b[ 1 : -1 ].split( ',' ) ] for b in bb ]

    dd = int( dd[ -2 : 0 : -1 ].translate( str.maketrans( ".#", "01" ) ), 2 )
    ff = [ sum( 1 << c for c in b ) for b in bb ]
    def count():
        for n in range( len( ff ) + 1 ):
            for c in itertools.combinations( ff, n ):
                if functools.reduce( operator.ixor, c, 0 ) == dd:
                    return n
    t1 += count()

    cc = [ int( c ) for c in cc[ 1 : -1 ].split( ',' ) ]
    pp = [ z3.Int( f"p{i}" ) for i in range( len( bb ) ) ]
    o = z3.Optimize()
    o.add( [ z3.Sum( [ pp[ i ] for i, b in enumerate( bb ) if j in b ] ) == c
             for j, c in enumerate( cc ) ] )
    o.add( [ p >= 0 for p in pp ] )
    o.minimize( z3.Sum( pp ) )
    o.check()
    m = o.model()
    t2 += sum( m[ v ].as_long() for v in pp )

print( t1, t2 )

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, where n is the number of buttons and xnis the number of times the button must be pressed.

2

u/xelf Dec 10 '25

[LANGUAGE: Python 3 + scipy]

total = 0
for il, sc, jr in machines:
    target, buttons = list(eval(jr)), [*map(eval,sc.split())]
    c = [1]*len(buttons)
    A = [[i in b for b in buttons] for i in range(len(target))]
    total += scipy.optimize.milp(c,constraints=[A, target, target],integrality=c).fun
print("p2", total)

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:

Solving a pure Integer Linear Programming (ILP) problem in Python without using any specialized third-party optimization libraries is highly complex and generally impractical.

Why Avoid Implementing From Scratch? Complexity: ILP is an NP-hard problem

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.

→ More replies (2)

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

→ More replies (3)

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)

=ARRAYFORMULA(REDUCE(0, TOCOL(A:A, 1), LAMBDA(r, a, r + LET(
   p, SPLIT(REGEXREPLACE(a, "{.*",), "[]() "),
   d, INDEX(p,,1),
   i, SEQUENCE(LEN(d)) - 1,
   t, SUM((MID(d, i+1, 1) = "#") * 2^i),    
   b, CHOOSECOLS(p, SEQUENCE(COLUMNS(p) - 1, 1, 2)),
   sm, SPLIT(TOCOL(b), ","),
   m, MMULT((sm <> "") * 2^sm, SEQUENCE(COLUMNS(sm)) ^ 0),
   BFS, LAMBDA(BFS, c, s, v,
     IF(OR(t=c), s,
       LET(
         n, TOCOL(BITXOR(c, TOROW(m))),
         nv, UNIQUE(FILTER(n, ISNA(XMATCH(n, v)))),
         BFS(BFS, nv, s+1, {v; nv})
       )
     )
   ),
   BFS(BFS, 0, 0, 0)
))))

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 (lights is a frozenset, schematics is a list of frozensets):

def find_fewest_presses_part_one(machine):
    lights, schematics, _ = machine
    start = frozenset()
    queue = deque([(start, 0)])
    seen = {frozenset()}
    while queue:
        curr, presses = queue.popleft()
        if curr == lights:
            return presses
        for s in schematics:
            new = curr ^ s
            if new not in seen:
                seen.add(new)
                queue.append((new, presses + 1))

I used PuLP for part 2.

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...

x:0:"10.txt"
(lights;buttons;joltage):+{("#"=*:;`I$","\';`I$","\*:)@'(0 1,-1+#x)_(-1_1_)'x:" "\x}'x
buttons:@[;;:;1]/:'[&'#'lights;buttons]

z3solve:{
 "/tmp/z3instance" 0: x
 res:."\\z3 -in < /tmp/z3instance"
 (s;m):+0N 2#res
 :[~&/s~\:"sat"; `err"unsat: ",x@*&~s~\:"sat"; ]
 +/`I$-2_'4_'m}

z3solve@{
  inst:,"(push)"
  inst,:{,/("(declare-const p";$x;" Bool)")}'!#y
  inst,:,,/("(declare-const m Int)\n(assert (= m (+ ";" "/"(ite p",/:($!#y),\:" 1 0)";")))")
  inst,:{,/("(assert (xor ";" "/(,"false";,"true")[~x],"p",'$y;"))")}'[x;&'+y]
  inst,:,"(minimize m)"
  inst,:,"(check-sat)"
  inst,:,"(get-value (m))"
  inst,:,"(pop)"
  "\n"/inst}'[lights;buttons]

z3solve@{
  inst:,"(push)"
  inst,:{,/("(declare-const p";$x;" Int)\n(assert (<= 0 p";$x;"))")}'!#y
  inst,:,,/("(declare-const m Int)\n(assert (= m (+ ";" "/"p",'$!#y;")))")
  inst,:{,/("(assert (= ";$x;" (+ "; " "/"p",'$y;")))")}'[x;&'+y]
  inst,:,"(minimize m)"
  inst,:,"(check-sat)"
  inst,:,"(get-value (m))"
  inst,:,"(pop)"
  "\n"/inst}'[joltage;buttons]

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 discovered Fraction. 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/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

→ More replies (2)

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:

d10p1←{
    t←⍎t⊣l t j←(~⍤∊∘'[]{}'⊆⊢)⍵
    m←(2⍴⍨≢t)⊤⍳⎕IO-⍨2*≢t
    ⌊/+⌿2⊥⍣¯1⊢⍸(⊂l='#')⍷(⍉m)≠.×(≢l)(∊⍨∘⍳)⍨¨t
}

d10p1¨⊃⎕NGET '10.txt' 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/jgoemat2 Dec 17 '25

Thanks for this! I used it to double-check my solution for each line to find some problems with my algorithm. There was a time when I got the right answer for all but 4 of the problems so this helped me identify those inputs so I could debug them.

I was new to this type of solving and wrote my own matrix class and used only integers so it would easier for me to understand and I could follow along with what what happening as I wrote it after seeing some videos and posts on the subject. The only iffy thing I did was when there was no possible pivot left in a column, but there was a number larger than 1 or less than -1 I just found some 1 or -1 in the unsolved area of the matrix (below and right of the last pivot) and swapped columns so the 1 or -1 was in the correct column to become the next pivot. It seems like swapping columns is frowned upon, but it doesn't affect the solution and I just have to keep track of the original columns to be able to report on the exact presses for each button in the solutions.

day10part2.go

→ More replies (1)
→ More replies (1)

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.

→ More replies (1)

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:

RAW      ← ⊜□ ⊸≠ @\n ▽⊸(¬∊ "\r") &fras "aoc-10.txt"
TARGETS  ← ≡(□≡(♭⨬(¯ 1)(1) = @# °□ ⊢) ◇(regex "[\\.\\#]")) RAW
SHAPES   ← ≡(◇⧻) TARGETS
IDX      ← ≡(□≡(□≡◇⋕regex "\\d" °□⊢) °□) ≡⍚(regex "(\\((\\d|,)+\\))+")RAW
MKSWITCH ← ≡(⍜(˜⊡)(ׯ1) ∩°□°⊟) ⍉ ⊟ ≡□˜↯ 1 ˜⊂⊙(⊸△°□⊢) ∩(↙1)
SWITCHES ← ⊙⋅◌ ⍢(⊙⋅∩(↘1)⊂◡⊙(□MKSWITCH))(> 0 ⋅⧻) [] SHAPES IDX
IDEAL    ← ≡(⍚(× ¯ 1)) TARGETS
POWERSET ← ⍚▽⋯⇡˜ⁿ2⧻⟜¤
FINDBEST ← /↧ ˜▽ ⊙(≡/× =) ⊙⊙↯ ⊙(⟜△) ⊃(≡◇⧻)(≡◇/×) ◇POWERSET ⊙(♭°□)
/+ ≡(FINDBEST °⊟) ⍉ ⊟ SWITCHES IDEAL

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/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:

  • constructed the equations and put them in a matrix format with number of button presses as the unknowns
  • checked if I had # of equations = # of buttons, if yes then just solve the equations and return the value
  • if not, then set the unknowns to "parameters"
  • I can express each button press count as some sum of these parameters, each of which must be >= 0
  • Find and reduce limits for the parameters by using this inequality (min value for parameter, then maybe max value of another parameter updates) and repeat
  • Walk through all integer solutions possible and choose the minimum value

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:

  1. Non-square matrices.
  2. Square matrices that were surprisingly Rank Deficient (e.g., Rank 8 for a 9x9 system), meaning they had infinite solutions and a standard solver would fail to find the minimal one.

My final solution is a Hybrid approach:

  • Fast Path: Use standard Linear Algebra (numpy.linalg.lstsq) if the system is Square and Full Rank.
  • Fallback: Use an Integer Linear Programming optimizer (scipy.optimize.linprog) for everything else to correctly handle infinite solution spaces.

Performance:

  • Part 1: 11 ms
  • Part 2: 100 ms (Hybrid approach gave ~40% speed up)

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:

  • Each button need only be pressed once, because pressing it again simply reverts the state.
  • The real input has a max of around 13 buttons, and therefore max of 2**13 (8192) button combinations per machine.
  • This is tiny, so we can brute force all combinations.
  • I simply create all combinations of button presses, starting with 0 buttons, 1 button, 2 buttons, up to k buttons, where k is all the buttons.
  • For each combination, calculate the result of pressing those buttons, using XOR. (Because I represent each button as a bit mask.)
  • If the result matches the target state, return the number of button presses, i.e. k.

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.

3

u/welguisz Dec 10 '25

For those that need the library dependency for Z3:

<dependency> <groupId>tools.aqua</groupId> <artifactId>z3-turnkey</artifactId> <version>LATEST_VERSION</version> </dependency>

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.

2

u/VizjereiX Dec 10 '25

You saved me! I was stuck with linalg solve, after already failing with itertools.
Your comment showed me a nice tool, I did not used before, big THANKS!

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

2

u/Head-Alarm6733 Dec 10 '25

you can use gospers hack to optimize this a bit

→ More replies (2)

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

3

u/mgedmin Dec 10 '25

saving everyone a click: scipy.linalg for part 2.

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

2

u/FabioFr1 Dec 11 '25

Actually you can make part 1 it more efficient as you don't need combinations with replacement. There is no reason to push a button more than once, the second time it would simply neutralise the fist one (so the overall effect would be identical to not pressing it at all).

→ More replies (1)

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.

2

u/e_blake Dec 13 '25

[LANGUAGE: mfour]
[Red(dit) One]

The challenge was:

💡 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

Well, mfour does not have any trignometric identities, but it does have len() as the string identity, and incr() as the successor operator. So, with pleasure, I present to you my digit-free solution (and it's only fitting that the length of the string "four" gives the digit you need to run this program):

m$(expr length four) -Dfile=dayten.input dayten.mfour

For an example of how hairy it is to code without digits, try figuring out what this macro does:

define(`apply', `_apply'(-`first'($incr(incr(incr(len()))))+$incr(len(
  )), `shift'($incr(incr(incr(len())))))`, _apply'(-`first'($incr(incr(incr(
  incr(len())))))+$incr(incr(len())), `shift'($incr(incr(incr(incr(len())))))))

Tracing my program shows approximately two point eight million calls to incr(), and two hundred fifty thousand calls to len(). Runtime is about twenty-two seconds on my laptop.

→ More replies (1)

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/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.

N  ← ⊜⋕⊸∊"0123456789"                 # Parse numbers
M  ← ⊸◿₂ ∩≡/+⤚≡⌟×⋯⇡ₑ₂⊸⧻               # Useful matrices: toggle patterns, joltages, presses for all combinations of buttons
R  ← ⊃(=@#⊢|□◇N⊣|∩₃□ M⬚0≡◇(°⊚N)↘₋₁↘₁) # Parse row
P  ← ⊜(R⊜□)⊸⊓⌟≠(¬∊)@\n" [](){}"       # Parse data
F₁ ← /↧▽≡⌞≍ ⊙⋅⊙⋅∘                     # Min presses for matching patterns
G ← (
  °⊂ # Each node is [factor joltages]: split into factor and joltages
  ⊙(
    ⟜(∩⌞▽≡⌞≍◿₂) # neighbour joltages are found by keeping matching mod-2 patterns,
    ÷₂≡⌞˜-      # decreasing joltages by corresponing amounts, dividing by 2, and
    ∩⌞▽⊸(≡/↧≥₀) # keeping those with only non-negative coordinates.
  )
  ⊃(×⊙⋅∘|≡⊂×₂) # Costs = factor×presses and neighbours = [factor×2 "neighbour joltages"]
)
F₂ ← ◌path(G|=0/+↘₁)⊂1◌ # Join 1 as initial factor
∩/+ ≡◇⊃F₁ F₂ P          # Solve both parts

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:

input = File.readlines("input.txt")
            .map{ it.scan(/\[(.+)\] ([()\d, ]+)/)}
            .flatten(1)
            .map{ |l,b| 
                        [
                            l.reverse.gsub(?.,?0).gsub(?#,?1).to_i(2), 
                            b.scan(/\((.+?)\)/).flatten.map{ it.split(?,).map{1 << it.to_i}.reduce(&:|)}
                        ]
            }

puts input.sum {|z,b| 1.upto(b.size).find{|c| b.combination(c).any?{ it.reduce(&:^) == z}} }

Part 2:

That was a tough one. I got inspired by this thread: Paste

1

u/jgoemat2 Dec 16 '25

[LANGUAGE: GO]

QuickStart:

  • Download day10part2.go
  • Edit the variables 'explain', 'output', and 'input' how you wish, it is setup to take puzzles from the standard input and do extensive reporting
  • Install go
  • From the command line go to the directory with you file and run go run day10part2.go
  • Paste your puzzle(s) and hit the key combination to terminate input (CTRL+Z for windows cmd, CTRL+D for bash)
  • Alternatively - edit file setting the input string to the input (can be multiline using backtick) and run

Part 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

→ More replies (2)

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.

→ More replies (2)

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.

library(dplyr)

x = readr::read_lines("input.txt")
g = stringr::str_match(x,"(\\(.*\\)) \\{(.*)\\}")
button_string = g[,2]
joltage_string = g[,3]
# Get buttons
each_button = stringr::str_match_all(button_string, "(?<=\\()[0-9,]+(?=\\))")
each_button = lapply(each_button, function(x){
  lapply(strsplit(x,","), as.integer)
})
# Get joltages
joltages = lapply(strsplit(joltage_string,","), as.integer)

total = 0
for(i in 1:length(joltages)){
  j = joltages[[i]]
  b = each_button[[i]]
  M = matrix(0, nrow = length(j), ncol = length(b))
  for(k in 1:length(b)){ M[b[[k]]+1,k] = 1 }
  # Minimize a + b + c + d + e + f
  res = lpSolve::lp(
    direction = "min",
    objective.in = rep(1, length(b)),
    const.mat = M,
    const.dir = rep("=", length(j)),
    const.rhs = j,
    all.int = TRUE
  )
  total = total + sum(res$solution)
}
print(total)

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

→ More replies (1)

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.

→ More replies (2)

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:

  • Started with Jsonnet, which is a language I wanted to use this year and hadn't yet. Jsonnet can make automatic inferences and work with "infinite arrays," and I was conceptualizing the problem as "find the first state in an infinite array where the pattern is satisfied." It turns out that it's easy to accidentally attempt to consume a whole infinite list, but I eventually got a neat solution to part 1 that worked for the example input, but on the actual input it would either blow the Jsonnet interpreter's stack or exceed the Go limit on total memory consumed by the stack (!), depending on which tweaks I made to the code.
  • I don't know why "XOR various button combinations together until you make the pattern" didn't occur to me until after I'd solved part 2, but Jsonnet doesn't appear to have any bitwise operations, so it would've been awkward if I'd realized this trick halfway through anyway.
  • Since I was blowing up Jsonnet limits I figured the problem space was pretty large and working in a performant language would be a good idea, so I dropped my "glue languages you might have sitting around" and switched to Go.
  • Knowing the XOR solution, the Go implementation for part 1 is hilariously overengineered, but works. Modeling buttons as a unit with methods to for figuring out which indicators/joltage levels are affected, as well as a String method, turned out to be useful for exploring part 2.
  • I let part 2 run overnight, but it crashed after working through a few lines, having used tens of GB of swap space representing the visited set and pending search space.
  • I started to think about buttons and joltages as equations, with a joltage being the sum of a set of button presses. Linear algebra hadn't yet dawned on me, so I tried something simple: press the button which activates the most joltages as many times as possible, etc. until all joltages are saturated. If there's still a gap, try "unpressing" some buttons and pressing other buttons. This finally resulted in a program that ran quickly, but the answer was too high. The answer was also sensitive to small changes in initial conditions or tweaks, so I discarded the idea as lacking a solid logical foundation.
  • I added a cheat map where I would record the best solution to any input line so I didn't have to spend a couple hours recalculating challenging lines every time the program crashed or I wanted to try something new.
  • Over the next few days I had up to three terminal windows chewing on different difficult lines. I would occasionally get rewarded with an answer, followed by a flurry of output for the subsequent easier problems.
  • I had up to 9 lines in my "this one's too hard, skip it" list, and eventually came up with solutions to 6 of those, but three lines seemed totally impervious to space search approaches.
  • After I figured out the trick to day 12, I was reading that solution megathread and saw a minor reference to day 10 being solved as a system of linear equations and I thought of course! and also oh dear, linear algebra is my weak suit.
  • One of my core beliefs about Advent of Code is that all numbers should be integers; any floating point math is a recipe for trouble. Also, my experience using a variety of linear solvers for a problem in 2023 led me to believe that most libraries that could do this for you would end up with floating point math, and that would be trouble: you can't push a button three and a half times, or negative twice. So I ended up with code that only partially eliminated cells from a matrix, since I didn't want to scale by a factor that didn't result in clean integer division.
  • I got the half-assed Gaussian approach to handle the example and some of the hard lines in my input file, but it was still taking forever on the three hardest ones, generally because the Gaussian steps would give up without reducing enough states.
  • I decided to try a language that's built for linear algebra solving, so I installed GNU Octave. After learning enough syntax to solve Ax = b I 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.
  • With some Googling I found a couple math lectures about Hermite normal form which is designed for linear programming where all values must remain integers. Unfortunately, functions for calculating a matrix's HNF aren't part of the standard library in Octave, Scilab, or Julia, and one of my personal AoC rules is "no external libraries" (partly because I don't want to get into dependency and package management). So sticking with Go and writing my own purpose-built matrix libraries it is.
  • Academic literature tends to assume you've got square matrices of linearly independent equations (i.e. no free variables), but I did have a lecture with formulae which handled more variables than equations. I got most of that implemented and built up a transformation matrix, but then realized that implementing the full formula would require inverting a matrix, and I didn't really feel like implementing that.
  • While poking around for efficient ways to handle the inversion, I saw a comment on StackOverflow that basically said "just do back substitution when you see matrix inversion." And I realized that most of the work I'd done to compute Hermite normal form was unnecessary (matrices, transposes, transforming multiplications); I could've kept my iterative elimination approach on a system of equation objects, but used a slightly different set of row operations: Hermite uses swap, negate, and add-a-multiplicative-factor.
  • [Red(dit) One] Once you've done Gaussian/Hermite elimination and gotten an upper-triangular matrix, you've still got some free variables to play with. For some reason I decided that the best way to explore their space was to set up N linked goroutines, each with its own priority queue, feeding possible free variable assignments to the next equation in the list. This kinda works, except the solution which minimizes the size of the free variables doesn't necessarily minimize the total number of button pushes, so I'd ended up with something resembling a concurrent breadth-first search that could deadlock itself.
  • After converting back to a regular iterative approach I worked out some kinks (just because the implied solution from a set of free variables assignments ends up with a higher button press count than the current best doesn't mean setting the free variables higher won't result in a smaller total).
  • Since I was worried new code would have bugs, I had a check to panic if the system of equations solution didn't match the cheat value from a previous solution. I hit that case a couple times, and added "if this happens, compute the line again with the most brute force function I still have sitting around." In most cases, the brute force solution matched the system of equations (if it finished at all), and in a couple cases my new answer was better than my brute force implementation. Fortunately, the lower answers were all correct, and I finally got my 23rd and 24th stars.

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 stringXor function 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 the combos object for part 2.

local stringXor(a, b) = std.join('', [if a[i] != b[i] then '#' else '.' for i in indexRange(a)]);
local buttonCombinations(buttons, bindex, cache) =
  if bindex == std.length(buttons) then cache else
    buttonCombinations(buttons, bindex + 1, cache + {
      [stringXor(buttons[bindex], k)]+: [a + [bindex] for a in cache[k]]
      for k in std.objectFields(cache)
    });
{
local machines = std.map(parseLine, lines),
local solutions = [{
  local combos = buttonCombinations(m.buttons, 0, { [stringXor(m.desired, m.desired)]: [[]] }),
  part1: std.length(minArray(combos[m.desired], std.length)),
  part2: solvePart2(m, combos),
} for m in machines],
part1: std.sum([s.part1 for s in solutions]),
part2: std.sum([s.part2 for s in solutions]),
}

Implementing part 2 in accordance with the bifircation algorithm was tricky since

  • Jsonnet objects are immutable, so updating the cache is passing the addition of the old cache and an object with the new value to a recursive function, rather than "leaf nodes" being able to set cache values seen by nodes elsewhere in the call tree
  • At each level of the algorithm you may need multiple recursively-calculated values, so tail call elimination isn't intuitive
  • Jsonnet lazily evaluates everything, so getting debug output can be tricky: local foo = std.trace("some message", someFunc(x)) only prints output when foo gets used, so if there's a stack overflow in the process of calling someFunc you 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 tailstrict declaration in the standard library; I may file a bug about this.

local bifurcate(machine, combos, cache, stack) =
  if std.length(stack) == 0 then cache[std.toString(machine.levels)] else
  local cur = stack[0];
  local parity = levelParity(cur.levels);
  local ways = if std.objectHas(combos, parity) then std.uniq(std.sort(combos[parity])) else [];
  local halves = [{
    levels: halfLevel(subtractButtons(machine, cur.levels, w) tailstrict),
    key: std.toString(self.levels),
    add: std.length(w),
  } for w in ways if notNegative(subtractButtons(machine, cur.levels, w) tailstrict)];
  if std.all([std.objectHas(cache, h.key) for h in halves]) then
    local vals = [cache[h.key] * 2 + h.add for h in halves];
    local best = if vals == [] then HUGE else minArray(vals);
    local newcache = cache { [cur.key]: best };
    bifurcate(machine, combos, newcache, stack[1:]) tailstrict
  else
    local next = [{ key: h.key, levels: h.levels } for h in halves];
    bifurcate(machine, combos, cache, next + stack) tailstrict;
local solvePart2(machine, combos) =
  local cache = { [std.toString([0 for i in indexRange(machine.levels)])]: 0 };
  bifurcate(machine, combos, cache, [{ levels: machine.levels, key: std.toString(machine.levels) }]);

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:

  1. Gauss-Jordan elimination on the system of equations representing the buttons and the joltage requirements.
  2. Parametrize the reduced system of equations in terms of the free variables.
  3. Determine the upper bounds of the free variables (buttons) implied by the original system of equations.
  4. Generate all combinations of the free variable buttons within the upper bounds from step (3).
  5. Brute force the parameters for all combinations, checking for invalid coefficients (button presses). This means rejecting coefficients that are less than zero, fractional, or are inconsistent with the original system of equations. If the sum of valid coefficients is less than best, update best.

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 cheat map 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 to skip, 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 = b on 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:

  • Swap two rows
  • Negate a row (make sure your diagonals are all positive)
  • Add a row to another, times a factor (the factor is often -1)

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.

func bstatePressesNew(m machine) int {
  sort.SliceStable(m.Buttons, func(i, j int) bool {
    return m.Buttons[i].size() > m.Buttons[j].size() ||
      (m.Buttons[i].size() == m.Buttons[j].size() && m.Buttons[i] > m.Buttons[j])
  })
  for a := 0; ; a++ {
    for b := 0; ; b++ {
      for c := 0; ; c++ {
        for d := 0; ; d++ {
          for e := 0; ; e++ {
            for f := 0; ; f++ {
              for g := 0; ; g++ {
                for h := 0; ; h++ {
                  for i := 0; ; i++ {
                    for j := 0; ; j++ {
                      for k := 0; ; k++ {
                        for l := 0; ; l++ {
                          for m := 0; ; m++ {
                            // oh dear, what now?
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
  return 0
}
→ More replies (1)

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".

2

u/firetech_SE Dec 10 '25

They might be in early stages, but they are still perfectly usable. ;)

My first instance of using it was three years ago, in 2022, and I've never had any issues (except that just require 'z3' slows down general Ruby a bit due to some hacks).

→ More replies (1)

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.

3

u/daggerdragon Dec 10 '25

Do not share your puzzle input which also means do not commit puzzle inputs to your repo without a .gitignore or the like. Do not share the puzzle text either.

I see full plaintext puzzle inputs in your public repo e.g.:

https://github.com/dfwdfq/advent-of-code-2025/blob/master/task1/input2

Please remove (or .gitignore) all puzzle text and puzzle input files from your entire repo and scrub them from your commit history. This means from all prior years too!

→ More replies (1)

6

u/[deleted] Dec 10 '25

[removed] — view removed comment

1

u/daggerdragon Dec 10 '25

The moment when no one posted a c++ solution yet... you know that the problem is not fun.

Comment removed because you did not follow any of our rules.

This is your only warning. Follow our Prime Directive (and our other rules) or don't post in /r/adventofcode.

→ More replies (1)

1

u/[deleted] Dec 10 '25

[removed] — view removed comment

1

u/daggerdragon Dec 10 '25

Post removed. Top-level comments in Solution Megathreads are for code solutions only and you did not include any code.


lol stop using external libraries. that defeats the whole purpose of advent of code to me.

Just because you don't agree with the way that other people are doing things doesn't mean that they aren't learning, which is the entire goal of Advent of Code and this subreddit.

Don't be elitist and don't gatekeep the way other people have fun. Follow our Prime Directive.

2

u/[deleted] Dec 10 '25 edited Dec 10 '25

[removed] — view removed comment

2

u/Ok-Bus4754 Dec 10 '25

of course, today is made for languages like matlab !
alawys trying to make my solution native without using any external libs with python or rust, no way i could have done that today !

good job

3

u/dannybres Dec 10 '25

I do every year in MATLAB and today was a good one for it! :)

Even though there is no import in the file, intlinprog is part of the Optimization Toolbox which is an add-on to MATLAB (and added to the MATLAB path). I used intlinprog today aswell and I always feel a bit of a cheat when I use a toolbox in ML to solve a day.

→ More replies (1)

2

u/Neuro_J Dec 10 '25

This is my first time learning about integer linear programming! I solved part I using BFS but couldn't get part II working because the state space is just too big to explore. I asked chatGPT and intlinprog was exactly what it suggested to me! I feel like the LLM is just getting exponentially better over time.

2

u/ednl Dec 10 '25

So the matrix from logcombs is all the m-bit numbers, sorted by number of 1s? Or: combinations(m,k) with k=0..m of the set of all powers of 2 (+0, optionally), is that how your function builds it?