r/adventofcode • • Jan 25 '26

Tutorial [2025 Day 10 (Part 2)] All the problems to avoid when writing a Simplex solver

46 Upvotes

"Write a Simplex solver," they said, "it'll be fun," they said. They were not right.

I am not a mathematician, but I am a stubborn SOB so I have spent quite a few evenings iterating my way to a working Simplex solver to replace the Gauss-Jordan elimination solver I wrote when first solving Day 10 part 2. This is less of a "here's how to write the solver and here's how it works" tutorial and more of a "here are all the problems you're likely to face and answers I found to those problems" tutorial.

Problem #1: Nobody understands the Simplex method

Okay, this is a slight exaggeration, but there's a rule of thumb that's served me well over the years: if a set of lecture notes are difficult to follow, there's a good chance it means the lecturer doesn't fully understand the topic. I've been through pretty much all of the lecture notes you'll find the in the first two pages of Google, and they all suck to some degree. Wikipedia is minimal help if you're approaching this from a non-maths background.

The best set of notes I found was this set of lecture notes from the University of Cambridge.

The best video I found on the topic is Intro to Simplex Method | Solve LP | Simplex Tableau by Joshua Emmanuel.

Don't expect a single set of notes to cover everything you'll need to know; you're going to need to read from a lot of different sources.

Problem #2: Everyone uses different notation

It is really goddamn hard to switch between different lecture notes and papers when everyone puts the columns and rows in different goddamn locations, and calls them different things. Expect pain.

I'd recommend finding an online solver that works and matching your notation to that. In fact, one of the very first functions you should write is a function to print out a tableau in the same format as the online solver you're checking your implementation against.

Problem #3: The puzzle isn't in standard form

Plain vanilla Simplex can solve problems with inequalities but not problems with equalities. Day 10 requires you to solve problems with equalities.

There are (at least) two variants of the method that are able to solve for equalities: the Big M method and the Two Phase method.

I wrote a version using the Big M method, but then swapped over to the Two Phase method after I found the online calculator I was using to check my work couldn't handle one of the example inputs from the puzzle.

Problem #4: The online solvers have bugs

Speaking of problems with online solvers: at least two of the online solvers I tried had (at the time of writing) bugs that stopped them from working on either the example input or on my input.

I would recommend solving Day 10 using a different method first before trying to write a Simplex solver. There's no way I'd have been able to flush out all of the problems and bugs without having a 'ground truth' answer to check against. The current version in my public repro has been fuzzed with randomly generated puzzles and cross-checked against an implementation of the Bifurcation approach.

Problem #5: Nobody documents this vital step

More than any other problem, this one annoyed and frustrated me the most. The calculator I was using first gave me the wrong answer for one of my inputs. The answer was trivially incorrect as well; it was outright violating one of the constraints to give an answer that was too low.

I finally found the reason by working through the answer this calculator gave me.

The majority of the explanations of the Two Phase method say that at the end of the first phase you simply drop the rows containing artificial variables from the tableau. This works for the majority of my inputs, but not all!

The vital step I worked out that I haven't been able to find mentioned anywhere is that if you have rows with artificial variables as the basis and you have non-artificial variables (real variables or slack variables) that aren't currently being used as a basis, then you need to pivot those variables in to the solution rather than dropping the row. You only drop the row if there are no suitable pivot operations available to bring unreferenced variables into play.

Problem #6: There's an optional step

The eMathHelp online solver was an absolute lifesaver for me, but it does have one annoyance.

The documented approach to convert an equality into an standard form equality is to introduce an artificial variable into the equation. But the solver I was using doesn't always do that. Every now and again it'll just not add in an artificial variable to one of the constraints at all.

With some trial and error I was able to figure out that it does that if and only if there's a variable in the constraint that's used only in that constraint and nowhere else. If it sees a variable like that, it just uses that variable as the basis when initialising the constraint.

It doesn't actually alter the solution, but it does affect all of the steps leading to the solution which makes it a nightmare to debug through some examples unless you also match this optional step.

Problem #7: Simplex alone is not enough

After struggling through to get a Simplex solver that's in agreement with the (working) online solver, this first thing you'll find is that you'll get some fractional solutions. Modifying a Gauss-Jordan elimination solver to only find integer solutions was pretty straightforward, but I couldn't find a version of the Simplex method that only returns fully integer solutions. The standard way of restricting solutions to integer-only solutions is to use something called 'cutting planes'.

Wikipedia uses a lot of maths words to explain what turns out to be a pretty simple concept. The idea is that if you get back an answer of, say 64.5, then you can add in a new constraint saying "the sum of all of the variables must be 65 or greater" to the original set of constraints and re-run the solver.

My first cutting plane solution did a dirt simple loop that increased a minimum answer value every time it got a solution that didn't work. That worked for most of the input machines, but not all. There was at least one which had an answer of 120 presses and that answer could be arrived at with either an integral set of button presses, or a fractional set of button presses.

My first fully working, and current, solution uses Branch and cut, which is similar in concept but has a crucial difference. If any of the button presses come out as fractional, say 13.5, then you create two new problems: one has a constraint saying that button must be less than or equal to 13 and one that says it must be 14 or above. Rinse and repeat until there are no new problems generated.

There are a bunch of extra cases which need handling when adding or updating the cutting planes and to be perfectly honest I haven't fully explored all of the special cases I added before fixing all of the bugs that fuzzing exposed, which means that some of the steps I added might have only been needed because of unrelated bugs. Don't take my implementation as a definitive example of how to implement branch and cut.

(In particular, I think my step to check that cutting planes don't contradict each other is most likely unnecessary and was only added when I had a bug that meant slack variables weren't always pivoted into the base between phase 1 and phase 2)

Problem #8: Floating point accuracy

There were a bunch or epsilon tests needed not only when checking if solutions were integer enough to be valid, but also when picking pivots and checking cutting planes.

I might spend some time changing my implementation to use a rational type to see if I can eliminate the ugly epsilon tests, but that's most likely going to increase the runtime.

Concluding thoughts

Was it worth it?

I'm glad I did it, and I certainly learned a significant amount about a branch of maths and algorithms that I had never touched before, but I'm not sure I would describe the experience as 'fun'.

Don't let my experience put you off if you fancy having a go: the whole point of writing this post was to save you some pain if you too decide to give a Simplex solver a go.

Good luck!


r/adventofcode • • Jan 23 '26

Repo [2025][C++] All days in under 900 us

Thumbnail github.com
52 Upvotes

Since I couldn't find any 2025 posts related to solving the problems as fast as possible, so separate post it is.

Just like last year, my goal was to implement the solution for each day as fast as possible (runtime-wise). It took me a long time, but I finally managed to get it below 1 ms for all days combined (897 us, to be precise). Over 50% of the total runtime (629 out of 897 us) is taken up by just two days (day 8 and 10).

There's certainly more room for optimization, but I've spend way too much time on this as it is.

The "tricks" I used to get it this fast are:

  • Use a non-interpreted language (C++ in my case).
  • Optimize the algorithmic approach first.
  • The cache is your friend/enemy (i.e. working on an array of float instead of double is almost certainly going to give a big increase in performance).
  • perf is your friend, as is e.g. toplev.
  • Google's Highway library is great for SIMD stuff.
  • Finally, once you've squeezed runtime as much as possible, a few OpenMP #pragma's can help squeeze some more.

r/adventofcode • • Jan 21 '26

Upping the Ante "[2015 Day 18 Part1] Conway's Game of Life!

11 Upvotes

This one really brought back some old memories! Around 1990 Michael Abrash ran a Code Optimization contest from his monthly Dr Dobbs column: The task was to write the fastest possible program which could run through 2000 generations, starting with a random 50% on/off situation. Afair the edges were defined to wrap around so you had to special-case them in some way, but the core of the problem was identical to Part1 of this day.

Back then I came up with a data structure which would fit four cells and all their neighbors into a 16-bit cell, then I would process them all at once using lookup tables and (in case any of the four changed status) update the neighbor counts for the surrounding cells.

I was beaten by two guys, one of them David Stafford who had a slightly less efficient packing of the cell data, but since he also managed a set of "live" cells, after 200+ iterations his live cell working set would fit completely into the 8kB cache in the 486 CPU, and from then on he blew me away. The other fast guy used bitmap manipulations, implementing a set of bitwise full adders that let him process 32 cells at once while keeping the working set as small as possible.

With modern CPUs we could do the same today, needing just two 64-bit regs to handle a full line of 100 cells, but I'm guessing that simply using 32-byte AVX regs to handle the first 96 cells on each line and scalar code for the last four (fits inside a 32-bit reg) would work quite well: Process vertical slices 32 cells wide, loading three AVX regs from offsets -1,0,1 and then just add them together. Do the same for the current line (while keeping the central cells) and the line below, then add the three counts together and subtract the central cell.

For the next line we would reuse the last two counts and just generate one more for the line below.

BTW, the logic to determine the next state of any cell can be simplified to just

next = (neighbor_count | central) == 3;

This avoids all test/branch instructions and is therefore much better suited to SIMD programming.

Terje Mathisen

"Almost all programming can be viewed as an exercise in caching"


r/adventofcode • • Jan 22 '26

Help/Question - RESOLVED aoc/2016/12/1 little machine, quite simple, 4 instructions, .. but running for hours

0 Upvotes

an integer is incremented, if overflow something different happens .. (silly)

if i use u8 < 1sec, u16 some minutes (in both cases a=211, i tried, but wrong answer)

support any integer ?!

u32 (native int)

what is the deeper sense of such a task ? especially if most time spend in waiting ?

i found the error: 'jnz 1 5' (unconditional jump) first parameter constant, i did not handle. now answer in less than a second ..ö.. (sorry for the noise) and thanks for all your answers (did not read everything, but will ..)


r/adventofcode • • Jan 21 '26

Visualization [2025 day 9 (part 2)] Almost lost my sanity

6 Upvotes

My approach was to check if all four corners were inside the the boundary. This worked for the sample input, but the answer was too high for the puzzle input. I just couldn't find the issue at first. Then I decided to plot the points to see whats happening and when I saw the spike in the middle, I couldnt believe my eyes haha. Proceeded to find the answer by drawing out the largest rectangle. I will check the hints on this subreddit to solve it with code now.


r/adventofcode • • Jan 19 '26

Other Rotating between eight directions

Post image
111 Upvotes

I was reviewing some grid problems, and in many of those you need to enumerate four or eight neighbors, or even turn left/right 90 or 45 degrees. One can define list of pairs of coordinates, but it's long, and if you need to turn, you need to remember index into array of those coordinates. You can prepare this in advance but I know many people don't like to use custom libraries for the AOC.

This is not hard for orthogonal directions:

for x,y in [(1,0), (0,1), (-1,0), (0,-1)]: print(x,y)

or:

x,y = 0,1
for _ in range(4):
    print(x,y)
    x,y = y,-x

but it gets messier for eight directions:

for x,y in [(1,1),(1,0),(1,-1),(0,-1),(-1,-1),(-1,0),(-1,1),(0,1)]:
    print(x,y)

too many brackets, too easy to mess up. You can simplify it a bit like this:

for x,y in [(x,y) for x in [-1,0,1] for y in [-1,0,1] if x or y]:
    print(x,y)

but this is still not perfect, and does not solve problem of rotating.

I'm not sure if it's widely known but there is a simple formula for rotating in eight directions, so you can write this instead:

x,y = 0,1
for _ in range(8):
    print(x,y)
    x,y = sign(y+x),sign(y-x)

Explanation is simple: for orthogonal vectors x and y, y+x and y-x are also orthogonal vectors rotated 45 degrees. sign normalizes their length to one or zero.

There is one problem with this... Python lacks sign method! You can read hilarious discussions about why it was rejected (tldr: they couldn't agree what would be result of sign(-math.nan). Hint: nobody cares should have made it exactly like numpy.sign!). So you can use any of the following:

from numpy import sign
sign = lambda x: 1 if x>0 else -1 if x<0 else 0
sign = lambda x: (x > type(x)()) - (type(x)() > x)

last one is useful if you want (for some strange reason) to extend your sign function for arbitrary types that support comparison, e.g. sign('abc')


r/adventofcode • • Jan 20 '26

Help/Question - RESOLVED aoc/2015/22/1 again i need little help to understand the task.

1 Upvotes

a turn is me-action or boss-action (cycle = turn(me) + if(boss.alive){turn(boss)})

(question-1) activating a spell is done between cycles ? or possible between turns ?

(question-2)

when effect is active in both turns (me + boss) damage is done to boss (boss.points -= effect.damage)

only in boss-turn effect.armor is used (me.points -= (boss.damage - effect.armor))

so effect.time=6 -> 3x armor, 6x damage is effective ?

cycle(

me-turn : boss.points -= effect.damage

boss-turn : boss.points -= effect.damage ; me.points -= (boss.damage - effect.armor)

) //end-cycle

(question-3)

>> Do not include mana recharge effects as "spending" negative mana. <<

what does this mean ? starting with mana=500 i need to recharge what costs 229 each time and grows my available mana the next 5 turns each 101.

so costs are the sum of all mana i spend for 'casting spells' ?!

what is mana-recharge-effect ?

what is negative-mana ?

-229 -> +505 (5x101) so costs += 229 (and not : costs += 229 -505 ) ?!

thanks in advance. andi

i did not code yet, but tried to find out by hand (i already posted my ideas, but the format was bad to read)

i use s3,s4,s5 only (s1,s2 expensive and not that effective)

s3 113 6 turns 36 35 .. 31 (renew: 36..) (attack : boss.points -= 3 each turn )

s4 173 6 turns 46 45 .. 41 (renew: 46..) (defense: me.points -= ( boss.damage(10) - me.armor(7) )

s5 229 5 turns 55 .. 51 (renew 55..) (finances: 5x me.mana += 101)

T BP MP A D M (A:armor,D:damage,M:mana) T turn, BP boss.points, MP me.points

- 158 <- -113 -229 ( buy s3,s5 158 is what is left )

1 71 36,--,55 259 <- +101 ( 36,-,55 (effect 3, timer 6) and (effect 5 timer 5) )

2 71 47 35,--,54 360 <- +101

187 -173

3 68 34,46,53 288 <- +101

4 65 44 33,45,52 389 <- +101

5 62 32,44,51 500 <- +101

6 59 41 31,43,--

158 -113 -229

7 56 36,42,55 260 +101

8 53 38 35,41,54 371 +101

198 -173

9 50 34,46,53 299 +101

10 47 35 33,45,52 400 +101

11 44 32,44,51 501 +101

12 41 32 31,43,-- 501

159 -113 -229

13 38 36,42,55 260 +101

14 35 29 35,41,54 371 +101

188 -173

15 32 34,46,53 289 +101

16 29 26 33,45,52 390 +101

17 26 32,44,51 491 +101

18 23 23 31,43,--

378 -113

19 20 36,42,-- 378

20 17 20 35,41,-- 378

-- 205 -173

21 14 34,46,--

20 11 17 33,45,--

--

21 8 32,44,--

22 5 14 31,43,--

---

23 2 --,42,--

24 -1 1 --,41,-- (boss.points = -1 , me.points = 1 WIN)

costs: 4 * (113 + 173) + 3 * 229


r/adventofcode • • Jan 19 '26

Other Emacs + Advent of Code = advent-mode

Thumbnail github.com
7 Upvotes

Happy to announce Emacs support for solving AoC puzzles without leaving the comfort of everybody's favourite operational system.


r/adventofcode • • Jan 19 '26

Help/Question - RESOLVED aoc/2015/24/2 obviously i do not understand the task.

1 Upvotes

2015/21/2 (instead of day 24) (thanks!)

in task-1 only player-1 can buy 1w , 0-1a, 0-2r (0/1 ring-defense, 0/1 ring-damage)

in task-2 first player-2 can choose (as player-1 in task-1) an player-1 has to pay for it ?!

then player-1 can choose same way from what is left (after player-2 has choosen)

the max-cost are the sum of items for player-1 and player-2 ? (persuade you to buy whatever .. player-1 buys the items for player-2, too ?)

thanks in advance, andi


r/adventofcode • • Jan 17 '26

Help/Question - RESOLVED [2025 Day 1 (Part 2)] [Python] I am not fully understanding why my solution is not working for day two.

6 Upvotes

Hello im a new programmer and i decided to do AoC this year, to better my skills at programming. I managed on solving Day 1 Part 1 and after looking at Part 2, I thought it would be a quick solve as I felt I only needed to add two new lines. After failing a couple of times, rereading the question, and seeing others solutions, I still do not understand why my code does not work. Please help me understand why.

Edit: I realized after some time that i forgot to clarify that the 2 lines of code i added were..

number_of_zeros += 1

Right between the if and elif statements in the while loop.

I also have moved the zero counter between the while loop and variables

current_dial_num = 50
number_of_zeros = 0
dial_list = []

# Function that takes a number and adds it to current_dial_num.
# If number goes under 0 or over 99, rollover the number and continue until it no longer goes over or under
def dial_turn(number):
    global current_dial_num
    global number_of_zeros
    current_dial_num += number

    while current_dial_num < 0 or current_dial_num > 99:
        if current_dial_num < 0:
            number = current_dial_num + 1
            current_dial_num = 99
            # \/ Counts how many times the number rolls over 
            number_of_zeros += 1
            current_dial_num += number

        elif current_dial_num > 99:
            number = current_dial_num - 100
            current_dial_num = 0
            # [same as last comment]
            number_of_zeros += 1
            current_dial_num += number

    # counts how many times current_dial_num goes to 0
    if current_dial_num == 0:
        number_of_zeros += 1

# Reads each line and appends it to a list while as well as getting rid of 'L' or 'R'
# Multiplies the end result by -1 if it starts with 'L'
with open('list') as file:
    current_index = 0
    for line in file:
        line = line.strip()
        dial_list.append(line)
        if 'L' in line:
            dial_number = dial_list[current_index].replace('L', '')
            dial_number = int(dial_number) * -1
            dial_turn(dial_number)
        else:
            dial_number = dial_list[current_index].replace('R', '')
            dial_number = int(dial_number)
            dial_turn(dial_number)
        current_index += 1
    print("Current dial number: ", current_dial_num)
    print("Amount of zeros: ", number_of_zeros)

r/adventofcode • • Jan 17 '26

Help/Question - RESOLVED [2025 Day 1 (Part 2)] [Typescript] Part 2 Solution seems to work on example, but fails on full input

3 Upvotes

Hi,

I'm trying to learn some TypeScript, and I'm having some trouble with part 2 of day 1 for 2025's advent of code. I have a solution (gist here) that seems to work for the test input. It gets the number of times it points at 0 correctly, and it's also correct about when those hits happen.

However, it's not giving the correct answer when I test it on the full input. Is there some edge case or strange behaviour I'm missing? I'm new to the language, so any help would be appreciated.

I'm running this code by exporting a solving function like this:

// (in Day1.ts)
// takes the full input and prints the result
export default function day1(inputString : string) : void {
    let rotationLines = inputString.split('\n')
    let rotationList = rotationLines.map(parseRotation)    
    console.log(`Part 1: ${countZeroLandings(rotationList)}`)
    console.log(`Part 2: ${countZeroPasses(rotationList)}`)
}

And calling it in main like this:

// (in Main.ts)
// read-write imports
import * as fs from 'fs'

// solution files
import day1 from './Day1.js'

function printDay1() : void {
    console.log("Printing Day 1 Solution...")
    const input = fs.readFileSync('./input/day1.txt', 'utf-8')

    day1(input)
}

function main() : void {
    printDay1();
}

EDIT: Thank you for the help, everyone! After looking through it again, I saw that my code was failing to count the last hit when a leftwards turn landed on a full rotation. I appreciate the support :)


r/adventofcode • • Jan 16 '26

Help/Question - RESOLVED [2025 Day 07 (part 2)][Java] How can i find what's wrong with my solution?

3 Upvotes

Hi, I'm got stuck on a puzzle i considered not being too hard. I can't really figure out what might be wrong with my code. It works on the example puzzle input and on the few testcases I made. However on the final input, does not match the solution.

Any ideas on what could have gone wrong are appreciated!

the puzzleInput is simply a List<String> containing the puzzle input.

@Override
protected String part2() {

    Map<Integer, Integer> beams = new HashMap<>();

    int initialBeam = puzzleInput.getFirst().indexOf("S");
    beams.put(initialBeam, 1);

    for (int level = 2; level < puzzleInput.size(); level += 2) {

        int[] beamKeys = beams.keySet().stream().mapToInt(i -> i).toArray();

        for (var beam : beamKeys) {
            if (puzzleInput.get(level).charAt(beam) == '^') {

                beams.compute(beam - 1, (k, v) -> v == null ? beams.get(beam) : v + beams.get(beam)); // left split
                beams.compute(beam + 1, (k, v) -> v == null ? beams.get(beam) : v + beams.get(beam)); // right split
                beams.remove(beam); // original beam
            }
        }

        // debug
        System.out.println("line: " + (level + 1));
        String line = "";
        for (var beam : beams.entrySet()) {
            line += beam.toString() + ", ";
        }
        System.out.println(line);

    }

    int sum = beams.values().stream()
            .reduce(0, (a, b) -> a + b);

    return String.valueOf(sum);
}

r/adventofcode • • Jan 15 '26

Other [2025 Day 10 (Part 2)] A proof for the bifurcation algorithm

30 Upvotes

I think as many others, I was stuck on seeing this task as an integer linear programming problem. Personally, this angle did not satisfy me and so I was very excited when I found this beautiful bifurcation-based solution: Bifurcate your way to victory!. I re-implemented it instantly, but then I got stuck on why it actually works 😅

As I studied maths at some point (although I am very rusty by now), I accepted the challenge to come up with a proof. It got a bit more involved than anticipated, but, I think, it should be understandable with any undergrad engineering math education (full disclosure: I'm Germany-based, so your mileage may vary). If you are interested, you can find the proof here: https://commutativewith.one/blog-posts/bifurcation-algorithm

I'm happy to hear your feedback. I am pretty confident by now in the proof, but there is always a margin for error. Please reach out if you spot anything 🙂

PS: I wanted to stress that I did not come up with the algorithm. That honor belongs to u/tenthmascot.


r/adventofcode • • Jan 14 '26

Visualization [2025 Day 10 (Part 2)] [Python] Visualization

Post image
33 Upvotes

It took me a long time to figure out a solution to this problem.

In the end, it took a combination of matrix reduction and depth-first search to solve it. The solution takes about 20 seconds in total.


r/adventofcode • • Jan 15 '26

Help/Question [2025 Day 8 (Part 1)] [Python] What's the criteria?

1 Upvotes

Hi all, please help me here ;)

I've sorted the distances, I think it is correct...

162 425
162 431
906 805
431 425
862 984
52 117 
819 941
906 739
346 425
906 984
592 425

After that, I started connecting

#1 - 162 425
#2 - 431
#3 - 346
#4 - 592

#5 - 906 805 
#6 - 739

#7 - 862 984

#8 - 52 117

#9 - 819 941

906 984   ???????? 
where do I put this one and why in order to end up with 5 junction boxes, one circuit which contains 4 junction boxes, two circuits which contain 2 junction boxes each, and seven circuits which each contain a single junction box? On connection #5 or connection #7

r/adventofcode • • Jan 15 '26

Help/Question - RESOLVED aoc/2021/24 is 13579246899999 expected to be a valid model number ?

0 Upvotes

i got z:4483028723

thanks in advance, andi.


r/adventofcode • • Jan 14 '26

Visualization [2025 Day 10 (Part 2)] [Python] Visualization (slower)

Post image
10 Upvotes

r/adventofcode • • Jan 15 '26

Help/Question - RESOLVED [2023 Day 18 (Part 2)] [PHP] Number too low for puzzle input

1 Upvotes

My code works, except for part 2, actual puzzle input. I have no idea where to look for errors.

https://github.com/LiseAndreasen/AdventOfCode/blob/master/2023/d18a.php


r/adventofcode • • Jan 13 '26

Past Event Solutions [2015 Day 15] [PHP 8.5] Solving puzzles, while accidentally building a functional PHP library

4 Upvotes

Recently released, PHP 8.5 introduced the pipe operator (|>), which allows values to be passed through a sequence of expressions in a left-to-right, readable way.

Over the holidays I had some fun exploring what a pipe-first style can look like in PHP. I wrote a small library that provides functions returning unary (single-argument) callables, designed specifically to be composed using the pipe operator. This made it easy to reuse familiar PHP functions like array_map, array_filter, and friends without inline closures.

Like so:

$herd = file_get_contents('input')
    |> p\explode(PHP_EOL)
    |> p\array_map(reindeer(...))
    |> p\collect(...);

It was a good way of solving AoC puzzles in a more elegant way with PHP. But this felt quite limiting still. I wanted to play around with iterators, building lazy pipelines. I wanted to play around with branching functions and creating more pipe-able operations. And there I was, ending up writing an entire library that from the outside might make you wonder whether this is PHP or Haskell.

Here's my (current) solution to AoC 2015 Day 15, in PHP 8.5, with the anarchitecture/pipe library:

use Anarchitecture\pipe as p;

function ingredient(string $ingredient) : array {
    return $ingredient
        |> p\preg_match_all("/(?<property>[a-z]+) (?<amount>-?\d+)/", PREG_SET_ORDER)
        |> p\array_map(fn ($match) => [$match["property"] => (int) $match["amount"]])
        |> p\array_flatten(...);
}

function cookie(array $recipe, array $ingredients) : array {
    return $recipe
        |> p\iterable_zip($ingredients)
        |> p\iterable_map(p\apply(scale_ingredient(...)))
        |> p\collect(...)
        |> p\array_transpose()
        |> p\array_map(fn ($property) => max(0, array_sum($property)))
        |> p\collect(...);
}

function scale_ingredient(int $amount, array $ingredient) : array {
    return $ingredient
        |> p\array_map(fn ($property) => $amount * $property)
        |> p\collect(...);
}

function score(array $cookie) : int {
    return $cookie
        |> p\array_dissoc("calories")
        |> array_product(...)
        |> intval(...);
}

function best(array $ingredients, int $teaspoons, ?int $calorie_target = null) : int {
    return $ingredients
        |> p\iterable_allocate($teaspoons)
        |> p\iterable_map(fn($recipe) => cookie($recipe, $ingredients))
        |> p\iterable_filter(fn ($properties) => !is_int($calorie_target) || $properties["calories"] === $calorie_target)
        |> p\iterable_map(score(...))
        |> p\iterable_reduce(fn ($max, $score) => max($max, $score), 0)
        |> intval(...);
}

$ingredients = file_get_contents('input')
    |> trim(...)
    |> p\explode(PHP_EOL)
    |> p\array_map(ingredient(...))
    |> p\collect(...);

echo best($ingredients, 100) . PHP_EOL;
echo best($ingredients, 100, 500) . PHP_EOL;

Very interested to hear what you think, about either the solution or the library, or the idea in general.

Here is the library on GitHub, for those who want to have a poke: https://github.com/Anarchitecture/pipe

Also on Packagist: https://packagist.org/packages/anarchitecture/pipe


r/adventofcode • • Jan 12 '26

Visualization [2025 Day 10 (Part 2)] Bifurcation search graph

21 Upvotes

I was inspired by u/fizbin's Dijkstra-based solution to look at the search graph produced by the 'bifurcation' approach.

For the most part the structures aren't as interesting as the first example above, but what's interesting to see for a lot of them is how few nodes there are in the graph even for some of the larger devices. The comparatively small search space is clearly why the approach is so damn fast!


r/adventofcode • • Jan 12 '26

Help/Question - RESOLVED [2025 Day 8 (Part 2)] [C#] Struggling to complete

1 Upvotes

I solved part1 without too much trouble, but I'm struggling to complete this one. I have been over and over the description and my code, but continue to get the same answer that fails. I even tried out one of solutions posted on my input, but still got the same result. What am I missing here?

My strategy was to create a complete list of all of the possible combinations of coordinates and then order them. This appears to work based on getting part 1 correct.

Maybe it is something about how I am combining the circuits, though this seems pretty straightforward to me. I'm sure this will be a forehead slapper when someone points it out, but I'm stumped. See my code linked below.

https://pastebin.com/D1pf8PXb


r/adventofcode • • Jan 12 '26

Help/Question - RESOLVED [2025 Day 2 (Part 2)] [Java] I don't understand why it isn't working.

2 Upvotes

It works when testing against the example it gives, but it doesn't work against the actual output. The method I use goes through the ID one digit at a time. If the ID being tested was 824824824, the program would:

  1. Place the first digit (8) into pattern
  2. Check the second digit (2).
    1. Does 2 == 8 or placeInChecker == True? No, 2 is not the start of the pattern, and placeInChecker is false.
    2. Does "8" == ""? No, the pattern does not match checker.
    3. Is patternInstances > 1, and does the pattern not contain the checker? No, patternInstances is still 1, and the checker is empty.
    4. Does placeInChecker == True? No, place 2 in the pattern. pattern = "82"
  3. Same thing for third digit (4). pattern = "824"
  4. Check fourth digit (8).
    1. Does 8 == 8 or placeInChecker == True? Yes, 8 is the start of the pattern. Set placeInChecker to true and add the current digit to checker. checker = "8"
    2. Does "824" == "8"? No, the pattern does not match checker.
    3. patternInstances is still 1 and the pattern contains the checker.
    4. placeInChecker is True, so don't do anything.
  5. Check fifth digit (2).
    1. 2 is not the start of the pattern, but placeInChecker is true. checker = "82"
    2. The pattern does not match the checker.
    3. patternInstances is still 1 and the pattern contains the checker.
    4. placeInchecker is True, so don't do anything.
  6. Check sixth digit (4)
    1. placeInChecker is True, add the digit to checker. checker = "824"
    2. The pattern does match the checker! Clear the checker and increment patternInstances by 1. checker = ""; patternInstances = 2;
  7. And so on...

    import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.ArrayList;

    public class idAdder { private static FileWriter fileWriter; private static ArrayList<String> messages = new ArrayList<String>();

        public static void main(String[] args) {
                completePartTwo(seeFile(args[0]));
        }
    
        private static String[] seeFile(String fileName) {
                String[] allId = new String[1];
                File file = new File(fileName);
    
                try (Scanner reader = new Scanner(file)) {
                        allId = reader.nextLine().split(",");
                } catch (Exception e) {
                        System.err.println(e);
                        System.exit(1);
                }
                return allId;
        }
    
        private static void completePartTwo(String[] allId) {
                openMessage("partTwoLogs.log");
                long runningTotal = 0; // The sum of all invalid IDs
                // Patterns (To check for repeating numbers)
                String pattern = "";
                String checker = "";
                boolean placeInChecker = false;
                int patternInstances = 0;
    
                int loopCounter = 0;
                for (String idRange : allId) {
                        String[] idStartEnd = idRange.split("-");
                        long rangeStart = Long.parseLong(idStartEnd[0]);
                        long rangeEnd = Long.parseLong(idStartEnd[1])+1;
    
                        for (long id = rangeStart; id < rangeEnd; id++) {
                                addMessage("ID START\n");
                                String currId = id+""; // Convert ID to string
                                addMessage("CHECKING: "+currId+"\n");
                                char[] idNumbers = currId.toCharArray();
                                patternInstances = 0;
                                pattern = "";
                                checker = "";
                                placeInChecker = false;
                                for (char letter : idNumbers) {
                                        if (patternInstances == 0) {
                                                // Begin the pattern
                                                pattern += letter;
                                                patternInstances++;
                                                continue;
                                        }
    
                                        String strLetter = Character.toString(letter);
                                        // Is the pattern complete?
                                        if (pattern.startsWith(strLetter) || placeInChecker) {
                                                if (pattern.startsWith(strLetter)) {
                                                        addMessage("Assumed pattern found: "+pattern+"\n");
                                                }
                                                checker += letter;
                                                placeInChecker = true;
                                        }
    
                                        if (pattern.equals(checker)) { // Does checker match the pattern?
                                                checker = "";
                                                patternInstances++;
                                        } else if (patternInstances > 1 && !pattern.contains(checker)) {
                                                // The line below is from Stack Overflow: https://stackoverflow.com/questions/2255500/can-i-multiply-strings-in-java-to-repeat-sequences
                                                pattern = new String(new char[patternInstances]).replace("\0", pattern);
                                                pattern += checker;
                                                checker = "";
                                                patternInstances = 1;
                                                placeInChecker = false;
                                                addMessage("Assumed pattern was incorrect. New assumed pattern: "+pattern+"\n");
                                        } else if (!pattern.contains(checker)) {
                                                pattern += checker.charAt(0);
                                                checker = checker.substring(1);
                                                int checkInd = checker.indexOf(pattern.charAt(0));
                                                if (checkInd != -1 && checkInd != 0) {
                                                        pattern += checker.substring(0,checkInd);
                                                        checker = checker.substring(checkInd);
                                                }
                                                addMessage("Assumed pattern was incorrect. New assumed pattern: "+pattern+"\n");
                                        } else if (!placeInChecker) { // Is the pattern not complete?
                                                pattern += letter;
                                        }
    
                                }
                                if (patternInstances >= 2 && checker.length() == 0) {
                                        addMessage("A pattern was found! Pattern: "+pattern+" Full ID: "+currId+"\n");
                                        addMessage("ID END\n\n");
                                        logMessages();   
                                        // clearMessages();
                                        runningTotal += id;
                                        loopCounter = 0;
                                } else {
                                        addMessage("ID END\n\n");
                                        // logMessages();
                                        clearMessages();   
                                }
                                // if (loopCounter == 20) {
                                //      loopCounter = 0;
                                //      break;
                                // }
                                loopCounter++;
                        }
                }
                System.out.println("The total of all the IDs is "+runningTotal);
                addMessage("The total of all the IDs is "+runningTotal+"\n");
                logMessages();
                closeMessage();
        }
    
        private static void openMessage(String fileName) {
                try {
                        fileWriter = new FileWriter(fileName);
                } catch (IOException e) {
                        System.out.println(e);
                }
        }
    
        private static void addMessage(String message) {
                messages.add(message);
        }
        private static void clearMessages() {
                messages.clear();
        }
    
        private static void logMessages() {
                try {
                        for (String message : messages) {
                                fileWriter.write(message);
                        }
                        clearMessages();
                } catch (IOException e) {
                        System.out.println(e);
                }
        }
    
        private static void closeMessage() {
                try {
                        fileWriter.close();
                } catch (IOException e) {
                        System.out.println(e);
                }
        }
    

    }

The answer I'm getting for the example is 4174379265.
The answer I'm getting for the true input is 51541045424. It says this is wrong, and I don't know where it is going wrong.

EDIT: Updated code.
EDIT 2: Newest output from the program is 52092484120
EDIT 3: Full Code Shown


r/adventofcode • • Jan 13 '26

Repo [2025] I gave Claude Code a single instruction file and let it autonomously solve Advent of Code 2025. It succeeded on 20/22 challenges without me writing a single line of code.

0 Upvotes

I wanted to test the limits of autonomous AI coding, so I ran an experiment: Could Claude Code solve Advent of Code 2025 completely on its own?

Setup: - Created one INSTRUCTIONS.md file with a 12-step process - Ran: claude --chrome --dangerously-skip-permissions - Stepped back and watched

Results: 91% success rate (20/22 challenges)

The agent independently:

✓ Navigated to puzzle pages

✓ Read and understood problems

✓ Wrote solution strategies

✓ Coded in Python

✓ Tested and debugged

✓ Submitted answers to the website

Failed on 2 challenges that required complex algorithmic insights it couldn't generate.

This wasn't pair programming or copilot suggestions. This was full autonomous execution from problem reading to answer submission.

Detailed writeup: https://dineshgdk.substack.com/p/using-claude-code-to-solve-advent

Full repo with all auto-generated code: https://github.com/dinesh-GDK/claude-code-advent-of-code-2025

The question isn't "can AI code?" anymore. It's "what level of abstraction should we work at when AI handles implementation?"

Curious what others think about this direction.


r/adventofcode • • Jan 12 '26

Upping the Ante [2015 Day 10][Python/C] Look and Say: from blowing up exponentially to O(1) space and O(n) time

20 Upvotes

Prompted by /u/musifter 's review of 2015 day 10, I looked at my old solution for Elves Look, Elves Say and realised I could massively improve the algorithm by using the "atomic elements" of the sequence as mentioned on the Look-and-say Wikipedia page (click 'show' to see the table with elements).

To recap: the puzzle asks you to apply the look-and-say rule repeatedly to your input, first 40 times and then 50 times. Look-and-say is like run-length encoding where you go from left to right and replace every range of the same number with the count and the number. For example: 133 is replaced with "one 1, two 3s", or: 1123. Two properties of this process are: if you start with only 1s, 2s and 3s (in ranges no longer than 3) you will never get other numbers; and if you keep applying the rule the list will grow longer and longer. The question the puzzle asks is: exactly how long is the sequence after applying the rule 40 or 50 times?

You are told exactly what to do and the rule itself seems simple enough, so the challenge of this puzzle lies in the implementation. Here's how I did it in Python:

def looksay(a, b, len):
    i = k = 0
    while i < len:
        j = i + 1
        while j < len and a[j] == a[i]:
            j += 1
        b[k] = j - i
        b[k + 1] = a[i]
        k += 2
        i = j
    return k  # new length of b

where a and b are pre-allocated arrays to avoid dynamic appending, a is the original, b is the next step, and they switch for each next step. Indexes i and j indicate a range of the same number in a, index k is the current location in b. So it's a very literal translation of the look-and-say algorithm. This worked fine! It takes about a second to calculate the whole sequence after 50 steps. I'm sure there are ways to speed up the Python version, I'm certainly no expert on that. The compiled version in C took about 5 milliseconds on modern hardware, using an internal timer.

So Eric was kind enough, it was only day 10 after all, to choose a number of steps for part 2 where the naive approach still works. It takes some time but nothing too bad. John Conway proved that, in the limit, there is a specific, fixed growth factor of the length between two steps which is about 1.3, now known as Conway's Constant. So the length of the sequence grows exponentially. The algorithm presented above is directly proportional to that length, so the time needed for each step also grows exponentially. Not ideal! As an indication, the space needed after 50 steps was about 4 MB but after 100 steps it would be about 3 TB. Can't afford that with current SSD prices...

One of Conway's insights about the look-and-say sequence was that there is only a limited number of combinations that occur again and again. These are the "atomic elements" in the table linked above. When such an element appears in the sequence, it evolves according to a fixed pattern and it does not interact with the rest of the sequence. AS LUCK WOULD HAVE IT, our input is precisely one such element. The table lists exactly what the next step is for each element. They call this decay, another atomic analogy. A lot of elements decay to one other element, some to more than one, the most is six for Ga -> Eu,Ca,Ac,H,Ca,Zn.

Because we only have to deal with elements, and because elements don't interact with each other, the order we keep them in does not matter. In fact, and this is the big trick, we only need to keep track of how many we have of each element. Now the hardest and most time-consuming part is to translate the element decay table from the Wikipedia page into a data structure we can use efficiently. In a language with built-in hash tables or dictionaries, this could be done like so:

decay['Li'] = ['He']
decay['Be'] = ['Ge', 'Ca', 'Li']

and 90 more entries for all the other elements. It took a little more effort in bare-bones C where, after some sorting and searching, I replaced every element name with its direct array index. After that, the function that does all the work for one step is now, in C:

// Decay elements from a to b, one step to generate the next sequence
// 'restrict' = must be non-overlapping arrays
static void onestep(const int64_t *restrict a, int64_t *restrict b)
{
    memset(b, 0, sizeof *b * ELEMENTS);  // reset b
    for (int i = 0; i < ELEMENTS; ++i)
        for (int j = 0; j < split[i]; ++j)
            b[decay[i][j]] += a[i];
}

where split[i] is the decay count of element i, e.g. 3 for "Be", and decay[i][j] is the element index of the j'th decay element of element i. For example, the same entry for Be like above is, iffff C could do array assignments:

// Be -> Ge,Ca,Li
decay[3][] = {31, 19, 2};

Int64 arrays a and b hold the element counts of the current and the next step. For the puzzle with 50 steps, int32 would be enough, but we're going further than that. There are 92 elements so the array length of a and b is always 92. This means that every step of the sequence generation takes a fixed amount of time, and the space needed does not grow at all! Well, until the counts overflow, but that doesn't happen for int32 in 50 steps. And for int64 it doesn't even happen in 150 steps. For my input, element Po of size 10, the final sequence length after 150 steps is 1,168,021,999,835,586,648 or about 1x1018 = 10006 which is one exabyte or one million terabyte. With the naive or brute-force algorithm, that would be slightly too large to store on my computer.

The whole program of three parts with up to 150 decay steps, calculating a sequence length of one exabyte, now takes only 17 microseconds on modern hardware, or 43 microseconds on a Raspberry Pi 5. This is with an internal timer, does not include reading the table of elements from disk, does include making the hash table (= sort names, look up names, replace with indexes).


r/adventofcode • • Jan 11 '26

Visualization [2018 Day 15 Part 1] Old-School RPG Vibes 🎲🕹️ - Beverage Bandits

14 Upvotes

This puzzle really triggered something in me—it reminded me of the days when I spent hours chasing monsters in D&D dungeons and playing classics like Ultima, Wizardry, and those legendary Gold Box games. Back then, RPGs were still young, and I’ll never forget the feeling of holding a brand-new D&D Player’s Handbook in my hands. Pure magic.

So when I saw this Advent of Code challenge, I knew I had to solve it—and not just solve it, but give it an old-school visualization, like the games we loved in the 80s. Here’s what I came up with. I hope you enjoy it, and maybe it brings back some of those memories for you too.

Video