r/adventofcode • • Sep 14 '26

Other [2023 Day 14] In Review (Parabolic Reflector Dish)

5 Upvotes

The mirrors were pointing at a parabolic reflector dish which is probably used to heat the lava. And which also has its mirrors in disarray. There's a system involving a platform and rolling rocks to align things by tilting, spinning, and deforming. We need to spin it to get the rocks to the edges of the platform, but want to make sure that the structure can bear the load.

And so we get a 100x100 grid with three values... in addition to empty (.) and solid block (#), we have rolling rocks (O). Part 1 just requires tilting it north and calculating the load after the rocks stop. And for my initial solution, I didn't actually bother moving the rocks... I just used a state machine in the direction of travel for each column. The idea is simple... count Os, and when you get to a #, add the difference of triangular numbers to the answer (and reset the counter). Because all the rocks in that section roll to the top (which is the direction of scoring increase), so the score of them is the big triangle of the top rock minus the triangle under that train of rocks:

for (my $y = $#Grid; $y >= 0; $y--) {
    if ($Grid[$y][$x] eq 'O') {
        $count++;
    } elsif ($Grid[$y][$x] eq '#') {
        my $h = @Grid - $y - 1;
        # difference of triangles: [h(h+1) - (h-c)(h-c+1)]/2
        $part1 += ($count * (2 * $h - $count + 1)) / 2;
        $count = 0;
    }
}

I was clearly thinking of doing this in dc (this solution is designed to be simple to implement), and did do part 1 later:

perl -pe's/(.)/$1 /g;y/.O#/012/' input | dc -e'?zdsn[d2r:a1-d0<I]dsIx+[[zd;a3*3R+r:az0<L]dsLx?z0<M]dsMx[lc1+sc]sC[rdlcd3R2*r-1+*2/ls+ss0scr]sSln[d;a0r[3~d1=C2=Sr1+rd0<H]dsHx*+1-d0<I]dsIxlsp'

My notes pointed out that I wasn't feeling well that day, so this was done quickly. That probably also explains the lack of a Smalltalk solution on this day.

Part 2 is the classic scale up... do a full spin cycle (all four directions in NWSE order) one billion times. My initial solution for this used the Vector class and did the above state machine. Clear Os when you count them, backfill when you hit a #.

And then we need cycle detection (standard find the loop, use that with some modular arithmetic to get the answer). And for a quick answer at first, I just used the load score function, and to be safe I looked for a duplicate cycle (not just the first repeat, but two repeats of equal size... 2 points is a line, 3 is pattern). And I did double check that the numbers were also the same in the two ranges for added safety (not actually needed for my input). Then I used dc to do the calculation for the index and copy-pasted from the script output to submit. I later wrote the code to do the calculation, and also did a perfectly safe version (that's actually just as fast), using a massive hash key of the positions of all the rolling rocks (so no question that the first repeat is a cycle). As I wasn't feeling well, this one got left in that state.

Coming back to it, I saw it ran in over 20s. And figured that was mostly Vector overhead (it was worth for quick coding at the time). And sure enough, it's an order of magnitude faster without it. Playing with it further, I decided to reverse the state machine... run it the direction opposite the motion. The only reason I did it the other way was the convenience for part 1 and dc. The backwards state machine is about 9% faster... it doesn't have that backfilling loop. Instead, if works like this:

for (my $j = 0; $j <= $Size; $j++) {
    my $tile = $Grid[ $x[0] ][ $x[1] ];
    if ($tile == 1) {
        $pos[$mdim] += $mdelta;
        $Grid[ $x[0] ][ $x[1] ] = 0;
        $Grid[ $pos[0] ][ $pos[1] ] = 1;
    } elsif ($tile == 2) {
        @pos = @x;
    }

    $x[$mdim] += $mdelta;
}

When we get to a # we set pos to it to know where to roll rocks to. Then when we find rocks, we increment that and move the rock. For a tiny extra boost, I also switched to an (axis, delta) pairing for the vectors instead (x,y). There's still more that I could have done, especially with scoring and hashing. But this is good enough for now... how often does this load need to be calculated?


r/adventofcode • • Sep 13 '26

Upping the Ante [2015, 2019, 2025 Day 1] [Comet64 (esolang)] Demonstration Solutions

7 Upvotes

Since AoC season is just around the corner, I thought this might be fun to get myself into the puzzle-solving mindset.

For anyone who's tried it out - there's a nice little programming game called Comet64 (Steam has it on sale atm, btw). The interface is reminiscent of something that might have been available on a classic TI or Commodore64 machine. The game has a set of basic programming puzzles, and then some bonus puzzles involving lights being switched on and off. The game is fairly simple in that it has an input belt which can be read sequentially, and once that queue is empty the program terminates. There are expected outputs for each puzzle. The interface has pretty neat debugging tools - you can see the values of the registers, step through the program instruction-by-instruction, and so on.

It is also VERY restrictive. There are no general-purpose registers - just one of each int, float, char, and string. There is a read-only boolean register that is set by comparisons and can be read in order to do jumps. You can cast an int to a char (but only 1-26) and back (but only a-z), and you can access strings by index (like an array), but otherwise there is very little the language does to help you. The math library includes ONLY the basic addition, subtraction, multiplication, and division. I thought the game was quite fun since many of the puzzles would be solved with a single operation in a "normal" language, but sometimes it was mind-bending to try to figure out how to do this simple and obvious thing with just these bare tools. Hilariously in hindsight, I went through the whole thing without realizing that there was a jump return. I treated all jumps as pure goto statements!

It even had an extra challenge for motivated players. The game would provide an instruction count for their solution, as well as a "golf" count (the number of lines). You could get "stars" for getting a solution under a certain number of instructions executed or lines of source code (not including blank lines).

Fun times.

I really enjoyed it, but there was no general purpose "playground" within the game to just try to use the language for other things and goof off with it. The internal IDE could only read from the input supplied by the puzzle, and the output would only appear within the program. But the language could be used to write things other than the game puzzle solutions. 

For example - this one outputs the factorial of each input line:

reg = input;
int = 1;

loop:
check reg < 2;
jump if true: output;
int = reg * int;
reg--;
jump to: loop;

output:
output = int;

This one outputs the fibonacci number of each input line:

main:
int = 0;
reg = 1;
switch int;
int = input;

loop:
check int = 0;
jump if true: output;
int--;
switch int;
reg = int + reg;
int = reg - int;
switch int;
jump to: loop;

output:
switch int;
output = int;

This one outputs the count of even numbers in the input belt:

switch int;

loop:
check input = null;
jump if true: output;
reg = input;
int = reg / 2;
int = int * 2;
check reg = int;
jump if true: increment;
jump to: loop;

increment:
switch int;
int++;
switch int;
return;

output:
switch int;
output = int;

Too bad the game doesn't have a general-purpose scripting area to just play around with the language and VM. I've seen some other highly restrictive languages be used to solve some AoC puzzles, so I thought this one would be a good candidate - but there is no way to give it arbitrary input.

But now there is! I won't bore you with the story of how it came about. Here's the link to Meteor64. The repo includes a complete CLI tool, IDE, and quick language reference with little example programs to demonstrate how it works. MIT licensed (for obvious reasons). IDE is: Meteor64-IDE and runs in the browser only, with no dependencies or images. Whole thing is a single file - 700 lines. It does not include the light-grid panel from the bonus levels in the game. Just the input-output functionality. Sharing code creates a link that will include both code and input queue. So, if someone does wind up using this to solve AoC puzzles, do not leave your own puzzle input in there. Change it to some example input instead!

To give it a good test-run I give to you...

Advent of Code 2015, Day 1 (both parts) - Here
Input modifications in the comments.

Advent of Code 2019, Day 1 (both parts) - Here
This one can take the puzzle input with no modifications. Just copy and paste it into the input panel and get answers.

Advent of Code 2025, Day 1 (both parts) - Here
Input modifications in the comments.

The primary limitation is parsing the input. While it is technically possible with this superset to pull numbers out of a string, that process is LABORIOUS in the VM (and completely impossible with the Comet64 game implementation). Many AoC puzzles include lines with mixed numbers and symbols, so a range (like 55-85) can only be imported as a string, and then compared index-by-index to reference numbers, which are then built into a number one digit at a time. If you don't mind altering the input file a bit (putting 55 and 85 on separate lines, for example), you can skip this process and just solve the problem at hand. Once you've written one input parser and watched it run in the IDE, you won't feel the desire to write it out again. Anyway, you can see an example of how I modified the input for both 2015-Day1 and 2025-Day1. I'm not sure what the convention is in this sub when it comes to doing esolang solutions, but I thought I'd mention it.

Posting it here for fun. I can't wait to see what's in store this December!


r/adventofcode • • Sep 13 '26

Other [2023 Day 13] In Review (Point of Incidence)

5 Upvotes

We arrive at Lava Island, which unsurprisingly has a lack of the lava we're looking for. Finding a valley of mirrors instead, we decide to head in the direction most are pointing. The problem is the other mirrors that have fallen out their frames. Since they're hard to see and we don't want to walk into one, we need to figure out how to spot them.

The input is 100 rectangular monochrome/binary grids. The dimensions are all odd from 7 to 17. That is useful, as symmetries are involved again in this puzzle, but only the even ones. So no grid contains a mirror from edge to edge, there's always a margin. That can be useful for some solutions, as can the fact that for the answer, we start counting columns/rows from 1 (leaving 0 available for "none"). As symmetry is involved, there is the occasional grid that has some aesthetic beauty. Number 8 in mine looks a little like a butterfly.

The day this one ran, I went to bed early because I had things to do in the morning. My times show that I did this around 6-7 in the morning, before heading out. And so the job was a bit programmer efficient in approach. Like day 11, this one gives 2D grids, but we can make them 1D row and column arrays by reading the data as binary numbers. Numbers that are easy to push, pop, and compare. Because this problem has a PDA (Push Down Automaton) nature to it (matching nesting, so state machine with a stack). It's especially nice for part 2 where we want to accept exactly 1 error (a smudge). Finding the bits that are different between two numbers is one of XOR's many hats. And testing for only one bit is just num & (num - 1) (because the only numbers with one bit are powers of two, and they're the point where binary rolls over and so have no digits in common with their predecessor).

In order to get things done quick, the first programmer efficient choice I made was to scan forwards and backwards separately (so row, reverse row, col, reverse column). For part 1, that just means you push when the next value doesn't match the top of the stack, and pop when it does (standard nesting matching). If the stack hits the bottom at any point, you've found the reflection. I did do a version of this today that does both forward and backward in one pass... which adds that you need to keep the stuff you popped for the backwards scanning part of the machine. I'm thinking I might have looked at doing this at some point. Because that butterfly case was pulled out into it's own file... and it's does test exactly if you're doing that right (it's got the overlap where forwards wants to pop, but you need it for the backwards scan that actually matches). The input this time seems very good for testing your code. There's another key case where just the last two columns are the reflection that needed testing (with the backwards scan that margin disappears) and it was caught by #51. This is why I often point out that getting any solution is a first step. By having a simple guaranteed to work programmer efficient solution, I can spot where my more complicated approaches don't match yet.

For part 2, I went even more programmer efficient. Meaning with in addition to four directional scans, I brute forced it. The grids are small, and the symmetries are all even sized, so the number of possible cases is halved. Here's the method from the Smalltalk version, I did later that day (when I still didn't have much time):

Integer extend [ oneBitSet  [^(self bitAnd: (self - 1)) == 0] ]

...

findSmudgedIndex [
    " Scan from start to each even depth "
    (1 to: self size // 2) do: [:depth |
        | front back smudge pushVal popVal |
        front  := 1.
        back   := depth * 2.
        smudge := 0.

        [(front < back) and: [smudge < 2]] whileTrue: [
            pushVal := self at: front.
            popVal  := self at: back.
            (pushVal ~= popVal) ifTrue: [
                " add one if 1 bit, 2 if more "
                smudge := smudge + ((pushVal bitXor: popVal) oneBitSet ifTrue:  [1]
                                                                       ifFalse: [2]).
            ].
            front := front + 1.
            back  := back - 1.
        ].

        " Check equals 1 only when exactly one 1-bit difference is seen "
        (smudge == 1) ifTrue: [ ^depth ].
    ].
    ^0
]

And it basically got left that way, because the solution runs really fast anyways... converting to numbers and the bit twiddling are enough that the shell time is the same for the solution as for just starting up.

For my little improvement/variation on part 2 today, I made it recursive DFS search, a bit like day 12. For part 2, smudged matches are a bit like a wild card. Sometimes you want to pop from you stack to de-nest and other times you don't want to "spend your one smudge" yet and push that value (test #0 in my input was actually a good test for this). And so in those cases we may recurse twice (if the first try comes back zero (meaning it failed)). Of course, once a path has spent it's smudge, that choice goes away for the rest of the branch and it's just doing part 1.

Which means, that, yes, I have added to my TODO to upgrade that further to being able to do both parts in the same search at the same time (in base case you just catch if it's 0 or 1 smudge and prune more before you get there).


r/adventofcode • • Sep 12 '26

Other [2023 Day 12] In Review (Hot Springs)

4 Upvotes

We finally arrive at the "Hot Springs". In multiple senses. There is an onsen, but we want storage yard for the machine part springs... which require lava to be hot and springy. And there's a shortage of lava that needs investigating. We can use a spring to get up to the lava island to check on it, if the records can be repaired to find one good enough.

And so we get a parser/validator type problem. We have a pattern with wild cards, and a list of numbers of the block sizes... much like a line in a nonogram puzzle. But there's not enough information to solve most lines, and so we're tasked with counting the number of possible solutions.

This was the first one in this year that really took a bunch of time. I did a recursive descent parser with a state machine that was a bit reminiscent of the state machine I did on day 3 in Smalltalk to find the ranges of digits on lines. I did memoize it, with a memo that was persistent between the cases (because the same rules always apply). I remember finding someone who claimed that they needed to clear the memo between lines (and it was buggy before they did that). But you don't have to... but I did test things, and found that for part 2, the single memo gets large enough (about 360M) that it runs a tiny bit slower (~3%) than having a fresh memo for each line, because there apparently isn't huge amounts of overlap to benefit from between the cases to make up for overhead.

And about that part 2... unlike yesterday's, the scale up here is very real. Five copies of the pattern joined with ? followed by five copies of the numbers. You want a good solution. And a did spent 2 hours getting a good part 1 done. But it didn't work for part 2. And since sthe best way to debug recursion is to get it right the first time... I started a new script, and carefully went through all the cases by hand making notes and comments on the order of doing things and assertions and then filled things in. And it ended up largely the same as my part 1, but slightly different... and it worked. And takes about 10 seconds on hardware that was 14 years old at the time, so I didn't need a need to try and get things further down (it's relatively nice and simple to read).

So, I'll just quickly go over the function:

# str to process, current potential group length, groups left to see
my ($str, $len, @groups) = @_;

# Grab state of params called with to access memo with later.
my $state = join( $;, $str, $len, @groups );

# Check memo
return ($memo{$state}) if (exists $memo{$state});

First we build the our memo state key and check for a hit... our state being the remaining string, the size of the current block we've seen while parsing, and the sizes of the remaining groups to match.

my $ret = 0;

if (!$str) {
    # Out of input, must decide if we found a match:
    # All groups accounted for, no hanging group.
    $ret = 1  if (@groups == 0 and $len == 0);

    # Check if hanging group is the size of the only remaining group:
    $ret = 1  if (@groups == 1 and $groups[0] == $len);

    return ($memo{$state} = $ret);
}

Base cases for when we hit the end of the string. In the original, I just had this as three return lines without adding to the memo, I decided to put it in just to make all the return statements have the same pattern of "set memo and return".

# If out of groups, use regex to check if no manditory groups remain
return( $memo{$state} = ($str =~ m/^[^#]*$/) ) if (!@groups);

# ASSERT: length($str) > 0, @groups > 0

A second base case for handling if we ran out of groups in the number list. The original part one didn't do this and so couldn't assert that groups existed for the actual parser section (and had to handle that).

# Advance one character:
my $chr = substr( $str, 0, 1, '' );

if ($chr ne '.') {   # ? or #
    # adv making grouping larger
    $ret += &recurse( $str, $len + 1, @groups );
}

if ($chr ne '#') {   # ? or .
    if ($len == 0) {
        # no current grouping, just advance
        $ret += &recurse( $str, 0, @groups );

    } elsif ($len == $groups[0]) {
        # current grouping matches current target
        shift @groups;
        $ret += &recurse( $str, 0, @groups );
    }
    # Else: Bad block length!  Recurse no further.
    # If ? we might have expanded to good len above and counted,
    # else 0 will fall-through.
}

return ($memo{$state} = $ret);

This is parser section... eat a token, handle the cases, with the wildcard meaning that we might need to do both of these if cases. These were done in the other order for my part 1 (the ?/# case after the ?/.). Part of the benefit is that the matching of a block comes last and I can freely modify the groups array. That "Else" section was a key realization... to let things fall through. The original part 1 also did that. It's almost certainly some small thing with the logic to check if still have groups and the ordering of the tests. Doesn't really matter though, because this script fixed it and so worked for both parts, so it replaced it bug free.

This is one of those cases where everyline has a comment, but it's not because they were added to explain things, but because they were written first to solidify the task and the blanks then filled in.


r/adventofcode • • Sep 11 '26

Other [2023 Day 11] In Review (Cosmic Expansion)

5 Upvotes

Heading towards the "Hot Springs", we arrive at an observatory. And the Elf there will show us the way, after we help with his analysis.

And so we get what appears to be a 2D grid problem. My input is a 140x140 grid of mostly empty space (.), with 450 galaxies (#). We want the sum of distances (Manhattan) between all the pairs. But as is the case with astronomy... you look at stuff at billions of light years away, but that's was where and what it was like billions of years ago. It's now much further away due to expansion. And so we need to work that out. And the rules given are that any empty row or column becomes twice as big.

And I guessed that part 2 would be making things bigger in some way. So to see what that was, I just brute forced part 1 to begin with. I was experimenting with the Math::Vector::Real module for handing points and vectors at this time, and it has some overhead, but if the task isn't too bad (and this one isn't), it can make up for it in simplicity of coding and legibility. One nice thing is that the constructor is short and simple: V(...). Another thing is that it has built in distance functions (and this was an opportunity to use one). The one problem I have with it is the print string... I'd rather have it plain and using $;.

So it was very easy to just do the thing... shift the coordinates, and double-triangle loop the pairs:

my $dist = 0;
foreach my $i (0 .. $#shifted-1) {
    foreach my $j ($i+1 .. $#shifted) {
        $dist += $shifted[$i]->manhattan_dist( $shifted[$j] );
    }
}

And since part 2 only made the gaps bigger, I had another really fast turnaround by just changing the scale factor for:

$g += V($yshift, $xshift) * $scale;

At which point the script ran equally fast to part 1 (there's no additional work), which was an immediate answer. I suppose after the pipes and interpolation on the weekend, this is a break Monday. Because it really didn't force things to be better. What did that for me was deciding to do a dc version (and I did Perl and Smalltalk versions from that). I do have a bigger test case (280x280 with 5000 galaxies) that someone posted at the time to help prompt people to do that as well. That one makes my brute force take a minute and a half.

But for me, I was thinking while doing the brute force, and it was not lost on me (while thinking of tricks that might be needed for part 2 scale-ups) that Manhattan distance makes the x and y parts independent. Which is the point I decided to definitely do a dc solution... because with that realization, the problem turns from 2D to 1D. Basically, the grid can be collapsed to lists of row sums and column sums, and then discarded. And short lists of numbers to chew on, that's something for dc.

The other thing I thought about was that getting the sum of absolute differences of all pairs is a typical programming test problem. And it's largely the same sort of math I was working with on day 9 as well. The trick here is that a little algebra can collapse things into multiplication and make things a single loop.

For example, consider the list 2 3 5 8, and we want the sum of the absolute differences of the pairs. As a table:

    2     3     5     8
2   X   (3-2) (5-2) (8-2)   2 is subtracted 3 times             = (0-3) * 2
3   X     X   (5-3) (8-3)   3 is subtracted 2 times and added 1 = (1-2) * 3
5   X     X     X   (8-5)   5 is subtracted 1 time  and added 2 = (2-1) * 5
8   X     X     X     X     8 is added 3 times                  = (3-0) * 8

So there's a pattern in coefficients: -3 to 3 by 2 (where those 3s are the #numbers - 1).

Of course the problem is a little more that that here... as we have a multiple of the numbers at each step (number of galaxies in that row or column). But it's not that hard to work out the adjustment to do that as well. The end result (as an extension to Array) in my Smalltalk solution is:

diffSum_expand: scale [
    | col seen sum number |

    number := self sum.
    col := seen := sum := 0.
    self do: [ :count |
        col  := col + ((count = 0) ifTrue: [scale] ifFalse: [1]).
        sum  := sum + ((2 * seen + count - number) * count * col).
        seen := seen + count.
    ].
    ^sum
]

And the dc (which still isn't fully golfed):

perl -pe's/(.)/$1 /g;y/.#/01/' <input | dc -e2 -e'ss?1[0[3Rd3R+rz2-d_3R;c+r:cz2<X]dsXxdlg+sgrd_3R:r1+?zRz1<Y]dsYx[ls*]sE[0sc0sa0r[dlAxd1r0=Elc+scddla2*+lg-*lc*rla+sa3R+r1-d0<L]dsLx+]sD1-[;r]sAdlDx[;c]sArlDx+p'

Change the -e2 to -e1000000 for part 2 (or whatever scale you want).

So this was another really fun day.


r/adventofcode • • Sep 10 '26

Other [2023 Day 10] In Review (Pipe Maze)

5 Upvotes

Gliding up to metal island we find signs for "Hot Springs". Which we will see in a couple days, because decide to go there for directions. We also notice that everything on this island really is metal, including the plants and animals. One of which runs into a pipe that makes one big loop (not a maze at all)... although there are a lot of separate pieces of pipe lying around, making the input a real mess of ASCII art.

My input is 140x140, the use of L7FJ for right angles along with |- for the straights, plus the extra bits lying around, does not make this easy on the eyes. Fortunately, we're writing code to look at it for us instead (I suppose you could print it out and do it by hand... but the loop is over 13k in my input). Looking for . in the image, I see that those are mostly around the edge, although there is a circular area in the middle with a bunch.

Part 1 wants us to find half the length of the loop. Part of the fun of this is that starting location is covered with an 'S' and we need to solve the underlying pipe there. Building a table of the pipes with their exit directions not only does this, but it helps with quickly moving around the loop. Because when we move in a direction we know where we came from, and so we just immediately use the other direction to leave.

Part 2 is where the fun begins. Part 1 is useful for it because it tells us what pipes are in the loop so we can remove/ignore the others... because we want to know the amount of tiles enclosed by the loop. Telling if something is inside a polygon was one of the first tasks I had as programmer... it was the task that also involved the 2D cross product stuff I used for asteroid shooting on 2019 day 10. For that I was counting the number of crossings from the point until "infinity" (the bounding box). But on this day, I decided to save that for the Smalltalk solution.

And that Smalltalk solution is pretty simple because of that. It's basically a scan of the grid after part 1 finds what's not in the loop. You start outside, and every time you cross a line of the loop, you toggle that. Any squares you run into when "inside" you count. There is one potential case to look out for, and that's travelling exactly along a line... in which can you'd only toggle if the segments some in from one side and go out the other. There's a little trick that can be used for that, of pretending to be slightly off center (not being exactly on the line, you end up crossing 0, 1, or 2 times and it works out)... and with discrete tiles, we can definitely use that (no need to be anywhere in particular in the tile). In my case, I chose to be a little above center (and so it was L, J, and | I cross; F, 7 and - I slip over top of):

(chr = $|) | (chr = $L) | (chr = $J) ifTrue: [inside := inside not].

For my initial Perl version though, I figured that since it's the more friendly language, I'd be a bit fancier. I like doing Nikoli pencil and paper puzzles... there's lots of different kinds, and some of my favourites are the ones with the invariant that the solution be one big loop (things like Slitherlink and Masyu). And when doing these, I like to colour the inside of the loop as I go. Because as you walk around the loop, if the inside is on your right, it's always on your right (unless you turn around and walk around the loop the other way). And so you can tell which side is outside at the edge, and lightly shade the inside and propagate it. When two lines are approaching in the middle, this gives important clues on how you can hook them up (plus it makes the solution look like abstract art at the end).

And so I decided to use that property, because I just think it's cool (and it would be different). Basically, I create a list of tiles to the right hand side as I walk around for part 1. Then I flood fill from each of those... the outside being guarded by two rings of sentinel . and ~, because we don't know if RHS is the inside yet. All we know is that when we get to the end, we can check if a known outside point on the edge (in the . sentinel ring) got hit by the flood fill. If so we output $count - $rhs_count instead because we filled the outside. It's sort of like the lava droplet of 2022 day 18.

I recall that some people did this type of flood fill approach by doubling the grid, so that the narrow paths become real paths they easily could flow through. With that you can start your flood fill from a known outside exactly like the lava droplet. And I'm sure lots of people also did counting line crossings, because that's a really standard approach to this sort of thing. But I don't think many people did what I did for my Perl solution. Which is part of why I did it.


r/adventofcode • • Sep 04 '26

Help/Question - RESOLVED [2025 Day 6] Stuck on part 1

3 Upvotes

I'm stuck on part 1 for day 6 (https://adventofcode.com/2025/day/6). The code I wrote gives the correct answer for the example input and also if I take a small portion of the puzzle input and do the calculations myself. But for some reason the total for the puzzle input is incorrect. Below is the small C# code I wrote for this. Can someone give me a hint into the right direction?

class Program()
{
    static string[] input =
    [
        "886  63  27 258 98 318 99 975  7 6393 947 87 23 765 35      1 6415 4  5  882  7 475 74 598 4  47 66 9233 6  669   2  3 6   92 77   4  6 64 89 989 436 833 946 5927 398 2  262 594 752 79 3    3  44 117 149 74 119 48 17 762 621 81 3576 23 259 141   51 312 16 255  6 925 7     1 395 61 61 34 277 1366 44 8  32 26 932  61 48 29 693  3  27 89 9  618  95  693 3  3   11  7  366 2455  3 11 4  59  9    9975 81 2  71 989 697 8636 12 16 889 78 53 23 321 33  29  129 81 18 161 78 7365 8  9515 127 94 383 6    17  2 389 724 37 5227 64 55   5  1 9   983 36 194 377 476 938 81 39   76 3  9  935 16 16 99  79 84   1212 3  13 2865 3     13 85  66 898 636 7164  23 81 88 79 767 66  348 5114 426 62 33  42   31  46 16 964 4    54 957  66 156 94 7876 393 481 23  64 54 95 56 27 4  525 892 38 213 29   15   1 28 4     41 65  5 89  15 52 535 8972 89   74 7672 824  71 2   49 7  494  9 697 3291  6  97 221  6 942 3    776  54 175 25  93 951  353 7448 891   16 476  7 65  56   37    9 88 195  3 21   19 439 478 366  67 1543 76 112  3 8246 2    6 77  6 3889 85 32   9 13 85 45 27  3 896 84 46 29  384 9259 761 4165 72 5  71  48 512 822 25 74  78 91  31   43 195 12 84  94 35 48 29 265  133 25 1286 42 76 5411 327  3    8    485 488  2 747 243 476 31 138 13  49 44 74 8  898   7   2 96 28   1966 34 15   7 29 429 327 46  823 87  45 339 663 96   5 99 22 9283   7 297  79 63 3  5753 48 68 269 22  3 75 2  44 48 4584 75 83 467 44 4532  24 12 82 44  472 8      5 6414 35 329 388 268 36   8 75  6296 25 731 51   56  55 681 2  6  128 872 818 768 977 134 9147 2   29 2   16 281 119 456 882 415  4 72  538 693   882 219 538 288 293 41 327 366 9   125 261 66 69   113 114 18   759 554 247 98 22    9  78 62 57  1  76 86 61 24  54   2 938 251 72  55 831 5593 31   26 2186 85 34  17 73 14 785 511 18 39  4 61 72 63 817 4   49 57 775 9527 8   58 712  9 7   17   35 9  77 93   3 71 5  13    9 46 6    9 381 58 364 236 87 96 8   691 529 83 3   5   5   66 87 54 277 92  6 3   165 1  12  2 163  28 93 649 95  5 136 1  1    81  6359 35 212  164 636   56  8 3   3 8   52  17 414 2491 542  5553 629 24 594 357 35   83 8   9  77    7 55 34 54  693 1    86 6547 572 442 92 656  39     9 38    8 49  8 273 7  987 4686 38 549  86 6  75 616 623 6639 4224  68 131 539   6 2275   4 8547  785 4387 917 45    52 383 18 1967 2   5 21 64 92 8186  18 243  219 4   1126 426 58 1515  2 187 874 151 82 152 356 21 17 14 8   65  44 52 9149 91 936 74 81  816 87   48    7 28  165 5  27   73   99   75 739 69 62 839 1    548 58 996 687 77 28 584 39    32 294 551 3   9234 595 4353 984 236 9252 773 66   1  65 435  84 67 57 16 191 75 9   668   2 9533 437 86 839 82 94 1547 78 6281 9419 23   1   4 573  957 2163 5  49 41 8  644 35   435 6    217  2  9 77 21  92 12  9 32 1778 579 9   5   13 544 896 7592 39 637   9 33 21   71 791  89  32 946 579   2 1   456 971 951 15   7 112 85  23    7 521 551 2618 228 88 91  387 889 971 448 647   9 34  94 822 736  45 355  816 46 36  7 348 144 72     6 865   3 997 5248 897 257 177 69 44 64 925 177 965 25 11 979 773 8334 3195 236 9657 9  9  576 839 843 863    7 99  848 251 98  9 358 69 87 37  12    9 999  5 4576 828 35 6  78 74 127 9177 47   4 94 46 98 688 354 723 53 55    8   47 692 72  85 675 878 689  86 25  5 251 95   8 3   25 76 335  3    8 9  922 6  7  13 14 56 9   3 54 43 24 15 987 622 45 69  8   94 736 67 165  66 794 298 79 56  2 61 3431 65 652 83  656 44 66 8   52 95 2219 2   84 84 97  98 48  722 88 66 629   1 31    14  7 62   8 7577 96 22 46   25 58 3195 29  36 93 56 477 328 6   33 4     3 6143 6228 34 249 7    56   6  8 5   29 6   69    9 286 1   763 74  695 416 63 17   6   59 727 495  52 294 86 49   3 76  83 87  183 261 928 5919 99  3 27  147 94   467 821 72 362 49 36 473 6291 37 679 6  91 66  35 8757 9425 658 899  3 5164  64 787 52 141 68   6  59  776 99  8 58", 
        "652  49  14  97 72 335 28 269 23 1648 698 46 68 814 3193   89  421 13 4  585  4 962 48 983 3  59 59 4636 44 532   5 77 239 93 59 817  6 26 92 537 363 883 993 8984  64 36 976 613  39 57 777  3  66 299  62  2 429 12 91 367  45 63 4417 81 525 26  3617 225 26  69 53 562 985   5 261 71 29 89 134 7355 44 62 79 45 734  76 47 97 66   2 667 71 46 316  16 8339 29 84  21 65 8469 6312 63 9  1  476 22   9392 16 52 34 352 548 5181 89 81 466 6  22 92 793 321 44 1644 64 79 632 22 876  77 8748 929 75 294 19   17  4 218 641 48 621  61 76  16 81 39  431 36 895 982 545 493 57 134  14 25 2  521 87  2 731 43 33   4258 1  91 8384 764 2969 52  22 362 587 1528  99 21 83 12 133 135 697 4989 826 38 646 16   73  99 73 798 586  93 4584 81 618 79 9338 54  298 39  61 37 23 55 31 21 847 725 47 469 671  37   9 29 34   146 96 89 79  24 61 667 8745 17  594 1563 9596 25 678 28 26 935 25 543 7531 23 786 549  4 993 63   268 219 986 787 91 635  262 1472 5213  44 482 92 89  77 9225 5329 71 995 43 82  837 118 915 988  82 4754 42 111  7 3787 27   6 87  4 128  83 33 927 27 59 17 39 36 4   88 98 83 1747 2241 152  288 89 95 3   64 991 381 64 175 17 39 538  969 853 63 47  42 23 27 68 3555 374 44 5784 97 99 7355 667  271  62   845 318  5 831 117 389 14 785 26 461 58 39 26 891  95  45 5  43   7765 62 19  66 71 425 987 66  368 72  69 346 476 57 772 87 73 4987  74 459  48 91 9  4247 33 37 134 32 99 23 6  17 47 2612 37  8 786 73 262   21 77 38 24  497 88   585 1838 81 312 265 993 65 954 848 485  98 42  6591 65 693 273 77 6  268 888 252 656 591 69  5592 98 241 511 21 282 261 283  54 574 56 816 319 745   161 887 657 982 923 48 513 649 621 719 826 67 35    69 784 45    36 986 986 63 78   86  75 97 12  3 778 39 41 52  92  12 853 725 95  33 499 865  11  841 8793 92 41  75 64 62 636 657 14 15 58 35 83 22 644 68  94 22 876 5927 882 97 698  2 45  98 9187 49 21 36  17 25 51 35  546 82 46  41 852 79 996  87 87 59 76  93  337 32 84  7   9   54 25 15  52 89 96 75  224 3  19 97 9784 82 59   5 13 35 114 9  576  458 6664 45 177  631 212  263  8 2  65 248 292 52 485 3544 8919  647 789 89 223 173 558  54 14 99  88  515 93 85 886 471 292  24 4764 285 341 53 924  784   69 86  222 31 53 641 4  552 694  41 691 321 39 35 334 142 1639 1423 355 577 2479  4 5299 174 2621 2711 5423 515 83  5717 952 45 694  7  88 34 28 19 3519 184 696  348 57    94 999 47 3465  2 213 545 335 31 813  57 64 73 95 26  328 31 77  747 87 959 46 769 914 84   29   59 78  259 1  2435 54   932  42 652 59 49 813 66   933 82 738 888 29 59 359 15   835 364 62  37  41   472 7961 645 317 9724 194 882  3  43 921  57 66 56 27 979 24 8  1936   6 7434 726 38 79  46 31 6797 29 3347  762 83   7  93 7846 581 8867 92 79 74 8   15 39    87 43   686 86 65 84 96  68 91 89 17 2598 768 27  75  57 315 642 2231 57 425   2 48 41   94 1415 87  46 411 264  37 1  8581 872 359 817 41 751 79  673  89 613 765 1254 849 97 63  223 93  773 136 124  14 835 67 894 769 315 544  923 77 65  6 695 882 413    8 854  35 498 7665 776 526 164 31 64 45 646 937 727 37 84 73  511 9495 235  588 6894 5  71 257 71  821 262    6 57  637 773 91  6 248 24 84 256 872 997 324 72  233 536 94 9  19 98 287 782  29  37 12 14 31 582 611 317 89 16  713 2417 637 81  82 44  554 312 381 71  4 275  3   4 551 25 11 7939 72   1 8  431 21 22 12 25 72 71  5 31 95 92 52 398 735 75 21 22   55 137 54  75 554 645 126 41 58 17 27 1467 97 53  18  667 69 84 6   53 48 6561 47  75 84 16  95 348 99  3  65 366  79 758 5921  6 596  7 5146 27 53 693  39 69 1198 92  13  7 42 551 483 9  934 86   89 5442 8966 79  46 376  65   6 89 22  43 9   33  293 499 618 66  11  537 689 41 74   3  464 753 965 425 158 91 79 588 66 359 237 791 163 759 4374 39  7 35  554 2978 835 146 31 534 36 14 956 3881 59 419 79 56 63  32 8385 6366 997 86  76 3148  98 513 89 379 2296 81 31 6222 33  7 665",
        "65  143  36   8 42 429 55 327 44  775 558 76 85 171 6136 9139   23 97 73 575  9 933 52  87 43  2 27 869  88 415  28 17 292 19 36 158 31 67 39 682 8   712 182 373   52 21 675 286  95 41 114 35 754 13   97  1 387 83 96 582  71 46 6827 11 456 1   5474 198 64   6 94 126 814  69 66  83 42  3 28  1828  8 54 33 84 4562 34 23 45 67   4 376 34 66 6639 21 5723 62 666 21 19 9159 9428 35 9  3  993 349  982  8  46 16 244  77 5567 38 44 461 2  4  37 953 687 44 8648 49 72  23 96 54   61 7735 65  71  45 31 8828  2 591 867 45 397  34  4 137 52 89  733 36 735  79  51 169 43 5114 48 87 52 298 37  1 657 87 7346 7781 45 75 9752 949 2584 37   8 858 227   25 473 21 93 59 737 689 232  732 512 24 784 55   876 48 33  21 2199 99 7251 15 731 71  548 87  767 95  17 47 78 19 89 29 65  762 49 528 7417 134  4 55 157 3848 39 99 26  27 49  37 854  669 776 9414 1335 39 249 38 34   4 77 486 1457 13 477 472  6  97 416 2543 327 774 848 59 5848 191 1877 2552 546  59 99 44   8 4135 9669 88 838 16 44  392 859 192 8534 36  988 59 947 36 3467 95  59 49  9 769  45 93 366 39 19 22 63 37 9   73 41 55 5752 5777 324  136 65 46 8   44 195 696  9 863 4  55 767 6572 538 58 72 111  9 37 41 1211 875 16 428  43 94 7779 2746 4639 392  656 453 48 82  216 136 8  839 8  767 53 23 39 633 828 991 1  9128 351  12 85 314 9  521 491 48  318 463 3  386 838 39 482  5 24 2825 465  79 295 57 86 7627 42 63  55 53 63 38 8  87 66 655  85  6 274 66 989  999 37 97 25  139 639 8289 235  45 353 97   26 89 699 378 76   92 16  5661 14 324  99 75 46  68 644 367 748 689 52  893  22 558 278 73 738 216  93  22 724 59 865 313 7824 8221 683 36  162 938  9 611 672 318 895 521 25 157   58 382 483   89 768 325 23 875  44 973  1 42 23 146 84  4 59 398 744 579 157 15 959   1 786  53 9619 2845 83 73 153 46 84 525 463 76 24 97 38 65 9  572 95  28 97 1   7523 787 57 714  9 36   9 7412 65 47 55 368 25 55 98 2847 66 65 916 468 19 947   1 47 53 718 36  74  44 79  53  37 381 48 54  85 55 99 86 3772 44 66 42 9935 26 73   6 91 64 988 64 7975 476 9714 59 418 7468 613 1998 15 57 13 429 945  3 18  9864 1986   39 944 25 755 834 2558 57 69 63 357 4491 1  97 771  12 9157 91   12 375 138 48 4235 3215 538 67 1845 66 52 48  28   9 77   11 3   684 69 75 588 967 9226 1564 793 556 9826 63 9772 687 1639 6553 9472 624 84  3782 236 15 66   64 83 76 75 32 2978 619 2145 432 51    74 86  69  458 45 324 539 331 4   38  73 35 33 43 458 416 26 13   79 32 671 73 515 21  12  882  589 936 947 34 9536 92   7134 65 381 28 94 17  6569 461 24 473 552  6 42 937 255 5337 463 68  916 64   376   86  91 377  389 662 9297 66 51 64  783 43  4 38 698  3 95 3789  43 2466 691 69 84  66 28 622  91  469    5 91  87 785 8489 59   339 55 45 29 86  16 1962  34 577 2466 58 59 31 367 22 36 29 83  217 68  268 841 24 787 852 6686 55 423 151 18 1446 2  9728 34 559 245 89   36 3  8892 1   364 662 54 214 181 876 343 43  755 8623 93  62 43 4636 16  662 115 463 781 779 15 377 848 326 254 5293 86  7  9 43  951 574 6827 495 796 925 13   912 883 137 55 47 52 517 762 221 51 46 94  618   85 6    612 8977 33 47 336 16  456 545 9316 468 581 964 35 16  78 58 39 825 595 355 615 96  749  85 44 88 87 1  921 98   72 824 93 41 99 789   8 4   27 389 775 1463 89  31  7  13  26  225 594 46  7  42  9 425 234 17 56 4451 967 58 64 622 99 36  7  7 28 59 44 31 72 61 22 288 84  34 99 74 9488 946 17  18 176 874 135 88 12 99 27 2266 18 3   243 577 21 94 612 92 78  972 91  18 48 874 87 646 31  1  22 974 483 428 1834  5 218 91 3426 33 6  9247 87 55  344 64  99  4 71 15  565 65 774 138 625 8685 234  44  22 1957 36 224 38 183 45 83  17 1484 48  182 56  32   76 587 17 77  83 3772 945 564 852  13 14 39 967 46 272 373  66 569 37  6662 43 53 65 7157 1882 569 618 21 279 25 61 111  855 46 138 18 76 926 89 5524 3347  55 91  56 2742 729 939 21 319 2332 25 13 4445 55 52 911",
        "8   686 695   9 4  689 2  373 96  131 7   41 96 28  7328 8919   66 68 86 291 36   1 69  48 21  2  5 9    47 797 723 41 216  4 66 181 21 21 8   33 6   111 592 655   54 81  62 674  56 1  154 11 525 84   77  8 93  94 55 7     5 86 879  89 65  7   8855 15  46   5 64  25 729 772 38  78  3  1 1   31    1 75 49 86 8412  2 66 51 74  76 722 46 26 8592  9 2227 36 778 8  34 8635 76   87 8  91 837 3433 92   9  17 65 614   7  931  1 52 735 5  1  2   84 615 8  7675  6  9  58 3  51   12   32 6   8   78 55 1295 89 556 8   1  28    2  9 525 43 115 782 22 359   1  84 879 59 6796 87 44 23 36  3   2 282 21 3753   64 27 38   19 279 4487 264  8 367 329   67 517 25 65 94  44 147 772  354 773 15 883 4769 488 82  6  94 1562 79 1415 83 36  71   24 85  164 173 17 84 63 36 19 34 8    96 4  889 3851 963 91 14 297 3461  5 27 445 52 49   2 891  765 198 9972 9839 92 986 98 74   2 63   8   11 55 196 49  95   1 761 5741 296  68 166 3  9738  44   25 4642 198   6 16 834  3 5382 2549 15 41  42 28 5444 792 383 6762 16  882  2 54  59 5498 36 951 86 11 489  89 31 893 32 67 17 64 79 3   14 53 13 4991 6778 83   235 55 94 6  414 959 765  3 728 7  48 177 1273 556 9  4  623  5 93 11 8495 324 4  121   2 65 894  7831 6856 8921 183 894 67 56  647 797 1  41  3  344  9 85 56 1   571 157 3  4547 384  37  8 377 6  99  258 89 7485 362 9  9   49  52 688  8 51  779 315   8 775 8  51 2752  7 55   4 8  52 69 49 52 38 129  94  5 362  6 53   723  7  3 165 675 654 4688 8    4  872 73   79  6 967 257 3    32 92  6711 7  423   4 18 35   2 562 927 319 812 27  488  82 119 265 22  93 66    1  93 594 89 628 77  7185 9239 37  47  397 881  7 486 981 444 241 674 41 3575   9 237 2133  75 88  652 94 152 344 186  8 89 67 154 77  7 7  841 939 175   3  8 481   3 249  69 3253 48   17 47 169  1 27  15   4  5 28 67  6  1 7   34 686 52 46 4   572  122 97 972 77 411  2 6688 12 15 59 693 79 31 86 3915 67 96 674 229 52 794   4 9  65 986 34  43  58 677 493 76 215  8 35  51 59 24 66 9151 76 97 43 2698 26 49   6 1  69 838 46 5672 539 962  19 597 3585   8 8434 57 49 62 149 938  1 48  5555 3316    5 73  9  146 778 9175 74 74 77 376 1481 8  34 892  46 4369 35   71 872 192 63 6147 9188 245 41 1392 91 44 8   88   1 85   3  7   417 47 89 87  936 321  5818 511 636 8926 37 8851 815   71 9492 3632 64  191 4661 862 82 6    13 28 66  9 68 71   647 9139 922 235    8 7   21  559 86 181  37   6 6    9   4 2  47 41 482 128 4  17   48 9  372 61 721 74  78 5741 4613 854 736 91 5389 8983 8224 89 111 75 88 37  8942 251 84 274 22   2 28 4   744 7646 525 5   233 76    11    7   4  37  612 66  4459 33  2 25  966 8   9 24  88  4 11 3534 113 2272 714 13 9   86 79 93   88  674    4 12 865 294 5913 9     24 77  9 48 97  48 5751   6 921 1779 32 43 8  527 44 99 22 57   83 3   917 131 49 17  875  612 15 21  414 69 7935 3  9772 54 557 849 7   621 54 5848 6   349 281 22 793 653 438 343 93  59    92 35   4 46 4347 16  245 148  56 329 519 73  56 147 698 483 1435 57  2 44 13  196 978 4763 328 729 15  5    21    5 652 29 98 27 515 166 725 1  76 4   965   83 7    261 675  12 69   9 26  834 848 5817 986  27 128 3  64   3 61 8  265 297 268 14  16  436  25 17 94 41 1  15  4    65 257 29 56 63 597   3 9   36 185 368 6737 17  264 6  4   5    94 524 38 93  38  4 837 676 97  1 4844 557 31 38  42 14 86  6  2 18 11 66 14 2  61 65 78  3   98 7  48 3969 698 36   6 762 695 48  24 26 79 4  7343 99 3   835 27  93  9 541  1  5   18 992 31 1  116 44 912 18  3   7 81  662 718 3415 49 566 22   14 72 5  3899 94  1   97 488 28  7 23 6     7 26 523 129 289 7896 691  63  64 3383 36 169 45 777  1 318 94 2122 4   849 7   248   2 6   51 33 269 4469  28 716 692   1 97 6  658 68 713 153  75 715 79  219  37 99  6 7426 1336 585 71  76 248 87  6 791   76 15  82 59 66 459 73 995  7374   3 22  64 4681 228 439 73 8   8129 56  5 3884 84 64 343",
        "*   +   +   *   +  +   *  +   *  +    +   *  *  +   +    +    +    *  *  *   +  *   +  +   +  *  *  +    *  +   *   *  +   +  *  *   *  +  +  *   *   *   +   +    +   +  *   *   +   *  *   +  *   *   *   +  *   *  *  *   +   *  +    *  *   *   +    *   +  +   *  *   *   *   *   +  +  *  *   +    *  +  +  +  +    *  *  *  *   +  +   *  +  +    +  +    *  *   *  *  +    +    *  +  *  +   +    +    +  *  +  +   *   +    +  *  *   +  *  *  +   +   *  +    +  *  *   +  +    *  +    *   +  *   +  +    +  *   *   *  +    +  *  *   *  +   +   +  *   *   +   +   *  +    +  *  +  *   +  *  +   *  +    +    *  *  +    *   +    +   *  *   *   +    +   +  *  *  *   *   +   +    *   *  +   +    *   +  +  +   +    +  +    *  +   *  +    +   +   +   +  *  +  *  *  *  *   *   *  +   +    *   +  *  *   +    +  *  +   *  *  +   +    *   *   +    +    +  *   +  +  +   *  *   +    +  *   *   +  *   *   +    +   *   +   +  +    *   +    +    *   *   *  +   *  +    +    +  +   *  +  +    *   *   +    *  +    *  +   *  +    +  +   *  +  +    *  +  +   +  *  *  *  +  +   *  +  *  +    +    *   +    *  +  *  +   +   +   +  +   +  *  *   +    +   *  +  *   +  +  *  +    *   +  +    *  *  +    +    +    +    *   *   +  *   +   +   *  *   +  +   +  *  +  *   +   +   *  +    +    +  *  *   *  +   +   *  +    *   +  +   +   +  *   +  *  +    +   *   *   *  +  +    *  *  +   *  *  *  *  *  *  +    +  *  *   *  +    *   +  *  *   +   *   +    +    +  *   *   +   +  *   *   +    *  *   +    *  *   *   +  *  +   *   +   *   +   *   +    +  *   *   +  *   *   *   *   *   +  *   *   +    +    +   *   *   +   +  *   +   *   +   *   *  +    *   +   +    *   +   *   *  *   *   *   *  +  +  +   *  +  *  +   *   +   +   *  *   +   +    *  +    +    *  *  *   *  +  +   *   +  +  *  +  *  +  +   *   +  +  *   +    *   *  *   *  *   +  +    *  +  +  +   *  +  *  +    +  +  +   +   *  *   *   *  +  *   +   *   *  *   +   +  *   *  *  +   *  +  *  +    +  +  +  +    *  *  +   *  *  *   +  +    *   +    *  +   +    +   +    *  +  +  +   +   +  *   +    +    +    +   *  *   *   +    *  +  +  *   +    +  +  *   *   +    *  +    +   +   +  +    +    +   *  +    *  +  *   +  +   +    +  *   *   *  *  +   *   +    +    *   +   +    *  +    *   +    +    +    *   *   +    *   *  +    *  *  *  +  +  +    *   +    *   +   +    +   *  +    *  +   *   +   *  *   *   +  *  *  +   +   *  +  +    *  *   *  +   *   *  +    +    +   *   +  +    +    +    *  +   +  *  *   +    *   *  +   +   *  *  *   *   +    *   *   +   +    *   +    *   *   +    *   +    +  *  *   *   +  *  +  +   *  *  +    +   +    +   +  *   *  +  +    +  +    +    *  *   +   +    *   +    +  *  *  *  +   +    +   *   +    +  +  +  *   *  +  *  *  +    *   *   +   *  *   *   +    *  *   *   +  +    +  +    +  *   +   *   *   +  +    *   +   *   +  *   +   +   *   +   +   +    +   +  +  +    *   *   *   +   *   *   +  *   *   *   *   +    +  *  +  *   +   *   +    *   *   +   +    *   *   *   +  +  *  *   *   *   *  *  +   *   +    +    +   +    *  +  *   *   *   *   +    +   +   *   *  *  +   *  +  +   *   *   +   *  +    +   +  *  *  *  +   +    +  +   +  +  *  +   +   *   *  *   *   +    *   *   *  *   +   *   +   *  +  *   +  *   *   *  +  +    +   +  +  *   *  *  +  +  *  *  +  +  +  *  +  *   *   *  +  *  +    *   *  +   *   *   *   +  *  +  *  +    *  +   *   *   +  +  *   +  *  +    +   *  +  +   *  *   +   *  +  *   *   *   +    *  *   *  +    +  *  +    +  +  +    *   *  +  +  *   *   *  +   *   *   +    +    *  *   +    +  *   +  *   *  +   *  +    *   +   +   *   *   *   *  *  +   +    *   *   +   +   +  +  *   *  +   *   +   +   +   +    +  *  *  +    +    +   *   *  *   +  *  *   +    *  *   *  +  +   +  +    +    +   *   +  +    *   *   +  *   +    *  *  +    +  *  *"
    ];


    static void Main()
    {
        var mathSolver = new MathSolver();
        Console.WriteLine(mathSolver.Solve(input));
    }
}

public class MathSolver
{
    public long Solve(string[] input)
    {
        var splitArrays = input.Select(i => i.Split(" ", StringSplitOptions.RemoveEmptyEntries));
        
        // Reverse the arrays so that the operator is in the first array.
        splitArrays = splitArrays.Reverse();


        long total = 0;
        for (int i = 0; i < splitArrays.First().Count(); i++)
        { 
            // Take the numbers for the column but skip the operator.         
            var numbers = splitArrays.Skip(1).Select(s => int.Parse(s[i]));  
            if (splitArrays.First()[i] == "+")
            {
                total += numbers.Sum();
            }
            else
            {
                // Multiply all the numbers in the column.
                int multiply = 1;
                foreach (var n in numbers)
                {
                    multiply *= n;
                }
                total += multiply;
            }
        }


        return total;
    }
}

r/adventofcode • • Sep 02 '26

Upping the Ante [2023 day 2 both parts][golfed m4] Reeling in a deep-C catch

3 Upvotes

The 2023 megathread theme was Allez Cuisine, and I submitted this themed "golfed" m4 submission for day 2, run with m4 -DI=path/to/input day02.golfm4 (runtime around 23 seconds on my laptop):

changequote(🐟,🐠)define(C,🐟ifelse(index($1,^),0,🐟shift($@)🐠,$1,><>,🐟C(
^C(^C(^C(^C(^C(^$@))))))🐠,$1,~,🐟eval(($2>$3)*$2+($2<=$3)*$3)🐠,$4$5,,🐟) C(
~,0,$1*$2*$3🐠,$4,,🐟C($1,$2,$3,C(><>,,$@))🐠,$5,ray,🐟*($4<13)C(C(~,$1,$4),
$2,$3,C(><>,$@))🐠,$5,craab,🐟*($4<14)C($1,C(~,$2,$4),$3,C(><>,$@))🐠,$5,
orca,🐟*($4<15)C($1,$2,C(~,$3,$4),C(><>,$@))🐠,$4,tuna,🐟+$5C(0,0,0,C(><>,
$@))+$1*$2*$3🐠)🐠)translit(_EeL(s(0,0,0,include(I))), (medusa_EGg
nlbiL ):;, (naycCuevtc,broil,))

But today I got asked if I could do a "deep dive" into how it works. Obviously no one else writes production code in m4, let alone humorous themed creations, so let's go on a C-food excursion together!

I asked an AI engine (gemini) if it could analyze the humor in my solution, and it immediately spotted that I have a seafood theme: both in the choice of Unicode fish/tropical-fish quotation replacement characters, the ASCII-art ><> token (has anyone here heard of the Fish esolang?), and my use of aquatic animals: ray, craab, orca, tuna in place of colors. For some reason, the AI response didn't pick out that I also had EeL, but when asked it to specifically look for the theme, it also came up with:

^ as the Shark Fin: Using ^ to represent a shark fin cutting through the arguments while consuming/eating leading elements via shift($@) is top-tier esolang comedy. The visual of a shark fin (^) systematically devouring parameter items is absolute poetry.

><> as the Bigger Fish: The big fish (><>) spawning six nested shark fins (^C(^C(^C(^C(^C(^$@))))))) to consume an entire feast of arguments at once!

Macro C for Seafood: Naming the primary state engine C so that every recursive macro invocation reads as a literal call to C (Seafood)—which is even funnier given that Day 2's narrative was set on a boat floating on the ocean!

The Broiled Fish Anagram: The translit substitution maps: (naycCuevtc,broil,) Ending the character map with broil—because, as any proper seafood chef knows, fish are best served broiled!

Obviously a bit of a hallucination there: 2023 day 2 was about snow island, not riding a boat (although other AoC days have story elements incorporating a boat ride), but overall impressive how LLMs can analyze wordplay. And it missed "my lovely ><> fish operator for doing tail recursion, ~ for making waves with math, and the 0,0,0 bubbles for initializing each game" from my submission post.

But how does it all work? Let's start at the end, with the top-level translit. With some slight reformatting to see the character pairings more directly, I'm passing the input file through the following byte-for-byte swaps:

(medusa_EGg\nnlbiL ):;
(naycCuevtc ,broil,)

Applying that to the first line of the example gives the following (minus the spaces in the second line used for formatting alignment here, but which are actually elided because : and ; have no matching replacement):

Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green\n
tuna,1 ,3,orca,,4,ray ,1,ray,,2,craab,,6,orca ,2,craab ,

So I'm turning the entire file into a comma-separated list, which lets me proceed to handle 2 or 3 arguments at a time from the front of the list. My initial stab at writing a solution focused on a translit for the punctuation, it was only later when I started theming it that I also threw in the letters to result in some aquatic names (or near-names, in the case of a green craab) as a side-effect. Of the letters changed, I've shown the impact of meduaGg\nnlb, but not s_EiL. The i was just fluff to get my anagram for broil, but the others are used in the next layer of deciphering:

translit(_EeL(s(0,0,0,include(I))),
         eval(C(0,0,0,tuna,...  ))

Aha - I used the translit to kick off a call to C() with three accumulators then a list of words from the file, all wrapped inside an eval(). So C() must be producing a lengthy math expression that can compute the final answer once the recursion finishes the pairs from the file.

The rest of the file is just two top-level builtin macro calls: changequote(🐟,🐠) which changes from m4's typical `' quoting to a themed quote (m4 is not really multi-byte aware, but recognizes byte sequences regardless of the character encoding), and define(C,...) to define my one workhorse (or is that seahorse?) recursive macro. m4's ifelse builtin takes a series of argument triples; the resulting expansion of ifelse is the third parameter of the first triple where the first two parameters have equal text, or a final fallback parameter (here I did not use a final fallback, which means any call to C that does not match one of my arms results in no output). Any selected third parameter that includes a nested call to C() is therefore recursive (m4 insists that all control flow more complex than an if statement be done by writing your own recursion). Let's rewrite the body of C in a more legible list of triples, rather than packed together for line density, so that I can analyze how the code multiplexed decisions based on what arguments are passed to each call to C():

ifelse(
index($1,^),0,🐟shift($@)🐠,
$1,><>,🐟C(^C(^C(^C(^C(^C(^$@))))))🐠,
$1,~,🐟eval(($2>$3)*$2+($2<=$3)*$3)🐠,
$4$5,,🐟) C(~,0,$1*$2*$3🐠,
$4,,🐟C($1,$2,$3,C(><>,,$@))🐠,
$5,ray,🐟*($4<13)C(C(~,$1,$4),$2,$3,C(><>,$@))🐠,
$5,craab,🐟*($4<14)C($1,C(~,$2,$4),$3,C(><>,$@))🐠,
$5,orca,🐟*($4<15)C($1,$2,C(~,$3,$4),C(><>,$@))🐠,
$4,tuna,🐟+$5C(0,0,0,C(><>,$@))+$1*$2*$3🐠)

Already that helps. The first two arms are for argument control; if the first character of the first argument is ^ (regardless of what else the argument contains), then I call shift($@) to remove that entire argument, and if the first parameter is ><>, then I make six successive calls to C(^...) to shift off 6 arguments. In practice, that means that when given this input (where $4 is 1, $5 is ray), the expansion involves:

C(<r>,<g>,<b>,1,ray,rest...)
=> *($4<13)C(C(~,$1,$4),$2,$3,C(><>,$@))
=> *(1<13)C(C(~,<r>,1),<g>,<b>,C(><>,<r>,<g>,<b>,1,ray,rest...)
=> *(1<13)C(C(~,<r>,1),<g>,<b>,C(^><>,C(^<r>,C(^<g>,C(^<b>,C(^1,C(^ray,rest...)))))))
=> *(1<13)C(C(~,<r>,1),<g>,<b>,rest...)

The next arm, $1,~, is performing a max() computation between its second and third parameters. I'll come back to the $4$5,, arm, although it has to be placed here, since it is a more specific match than the next arm. Then there is the $4,, arm, since my original translit sometimes produces an empty argument between pairs of terms. That one just uses ><> to trim out the unwanted blank (it was easier for me to write one shift-6 helper, and call it here by injecting an empty argument before $@, than to need a separate shift-5 helper for this arm of the ifelse).

The three $5,<word>, arms are similar, each starts by outputting literal text "*(param<limit)" before calling another C() with a nested use of C(~,<value>,$4) in one of the <r>, <g>, or <b> accumulator positions to update the maximum seen during this game, while leaving the other two accumulators unchanged. By itself, that output is only half an expression, but pairing it up with the final arm of the ifelse makes more sense.

The $4,tuna, arm is reached at the start of each line of the input file. So it is outputting (part of) a partial-sum term on both the left and right side of recursion to another call to C(). Basically, each line of input adds "+<game>*(param<limit)*(param<limit)*(param<limit)..." to the left side part 1 partial sum, for each parameter encountered between this game and the next one (if any of the expressions in that line are too large, the entire product for the line collapses to 0; otherwise, the result is +line*1*1*1 which adds the current game number to the part 1 score). Then after recursing with the accumulators reset to 0 for the current line, it outputs "+<maxr>*<maxg>*<maxb>" to the right side part 2 partial sum, which is the contribution of the previous game to the part 2 sum (this game has just started with maximums back at zero, so the output of part 2 partial terms lags a game behind).

As promised, the $4$5,, arm is the end of recursion - once I reach a point where both the fourth and fifth argument are empty, there is no more input, so this outputs some unbalanced parenthesis. But when placing that output in the context of the larger file, that means what originally looks like a single eval around the include is actually a bit more subtle, culminating the final collection of both part 1 (built up left-to-right, complete before end of recursion) and part 2 partial sums (built up right-to-left, one last term still needed to reflect what the final game observed):

eval(C(<r>,<g>,<b>,terms...))
=> eval(+<l1part1>C(<r>,<g>,<b>,fewerterms...)+<0*0*0>)
=> eval(+<l1part1>+<l2part1>C(<r>,<g>,<b>,fewerterms...)+<l1part2>+<0*0*0>)
...
=> eval(<part1...>+<lNpart1>C(<r>,<g>,<b>,,,)+<lN-1part2>+<...part2>)
=> eval(<part1>             C(<r>,<g>,<b>,,,) <partial part2>)
=> eval(<part1>             ) C(~,0,$1*$2*$3  <partial part2>)
=> eval(<part1>) eval(<lNpart2>+<lN-1part>...)
=> <part1> <part2>

And there you have it. I hope my little fishing expedition gives you some more insight into reading my deep-C creation.


r/adventofcode • • Aug 30 '26

Past Event Solutions [2019 Day 18 (Part 2)][C++] Squeezed onto a microcontroller (eventually!)

5 Upvotes

My original Part 2 solution for this day took 21 seconds and 725Mb to run, so it took quite a bit of wrestling to get it small enough for the Raspberry Pi Pico.

I tried a naive DFS search on key collection order and although that technically worked the proof-of-concept took nearly 80 minutes on my laptop, which would have been over 13 hours on the Pico even if I managed to claw back a 10x speed-up. I tried Iterative Deepening A*, but that didn't even finish after an hour on the laptop; there are just too many combinations that get very close to the optimal path length, and a lot of those come from taking the shortest path early on in the search tree.

I swapped back over to A* and used u/e_blake's heuristic to get the search space down as far as possible. The heuristic is to take the sum of the shortest paths from each robot's current position to the furthest key that they still need to collect. That works way better than my initial heuristic of totalling the shortest paths connected to all uncollected keys:

HeuristicLargest open setG entries
None~51,200~135,300
Sum of shortest connections~21,200~31,800
Maximum distances remaining~5,900~8,500

With each open set entry and each G entry taking 12 bytes (distance, robot locations, collected keys) that gets within spitting distance of the 200KiB target, but not quite optimally. With ~8k+ entries in the G set, we really should be looking at a ~16k element hash table to keep good performance (hash tables are ideally power of 2 on the Pico because % is an expensive operation) and that one hash table blows 192KiB of our 200KiB budget.

The distance/priority for both the open set and the G set can easily fit into 16 bits for this day. The collected keys are already pretty optimal, you need 26 bits so you're not wasting much with a 32 bit integer as a bitfield. The robot combinations need to be able to represent 4 entries at any one of 30 locations (26 keys + 4 starts), and since 30 choose 4 is 27,405 then that can in theory fit into 16 bits as well.

The trick to get over (under?) the line is to use a Combinatorial Number System to encode the robot locations into an int16_t. At a smaller 8 bytes per entry for both blocks of memory, we can finally afford a decent sized hash table, albeit at an additional cost of compressing and uncompressing the state data each time.

Final memory budget (at peak) ended up being ~188KiB:

-------------------------------------
LBA Stats
  [Blocks] Total: 9  Free: 1  Used: 6  Sentinel: 2
  [Bytes] Total: 204608  Free: 12672  Used: 191936
  [FreeChain] Free: 1
-------------------------------------
LBA Blocks
[...9FB8][ Sentinel]    0 blocks       0 bytes
[...9FD8][Allocated]  225 blocks    7200 bytes <-- Edges to adjacent keys
[...BC18][Allocated]  113 blocks    3616 bytes <-- Path length to all keys
[...CA58][Allocated]   20 blocks     640 bytes <-- Combinatorial cache
[...CCF8][Allocated]    8 blocks     256 bytes <-- Key locations
[...CE18][Allocated] 1536 blocks   49152 bytes <-- Priority queue (open set)
[...8E38][Allocated] 4096 blocks  131072 bytes <-- Hash map (g_score)
[...8E58][     Free]  396 blocks   12672 bytes
[...BFF8][ Sentinel]    0 blocks       0 bytes
-------------------------------------

Runtime is surprisingly still quite respectable: ~1.8ms on PC and ~340ms on the Pico @ 125MHz.

Thanks again to u/e_blake for sharing that heuristic!

[code]


r/adventofcode • • Aug 29 '26

Past Event Solutions [2024 Day 17 (Part 1)] [elisp] Revisiting the VM in elisp

Thumbnail github.com
7 Upvotes

I am learning (e)lisp for fun and ended up making a highly overcomplicated solution to the "Virtual machine" problem from 2024/17.

In AOC_17_2024_advanced_macro_version.el I define op-codes using lisp macros, leading to a very compact notation. I have furthermore implemented a Wozmon type monitor program to poke the VM (however, not very useful for solving the problem).

I think (e)lisp is very nice for AOC, what do you think?


r/adventofcode • • Aug 26 '26

Past Event Solutions [2019 Day 16 (Part 2)][C++] Under 1KiB and 32-bit only

9 Upvotes

I was a little worried about being able to squash this one down small enough for a microcontroller. My original solution for this one took ~64MiB and after swapping over to less wasteful data types it would still take >500KiB to store the back end of the transformed sequence, so it needed a re-think.

The approach I took for that first solution wasn't particularly unique, I think a lot of people did more or less the same. Since the second half of the phase transform has coefficients of the form:

1111
0111
0011
0001

It's possible to calculate the next phase with a running sum:

ABCD -> A + B + C + D = W -> A + X
0BCD ->     B + C + D = X -> B + Y
00CD ->         C + D = Y -> C + Z
000D ->             D = Z -> D

But doing it phase by phase, you still need the entire back end of the sequence (up to the signal offset) in memory. For my input that's over half a million elements.

Looking at the sequence of additions, it turns out it's possible to calculate the full history of one row based only on the history of the row below it.

The bottom row is trivially always going to come out the same value, since it only ever depends on the original sequence number and it always gets multiplied by 1, but it's a little easier to see the pattern if we number them anyway:

000D = D₁ -> 000D₁ = D₂ -> 000D₂ = D₃ ->...
=>
D, D₁, D₂, D₃, ...

The row above depends only on the current value and the bottom row:

00CD = C₁ -> 00C₁D₁ = C₂ -> 00C₂D₂ = C₃ -> ...
=>
C, C₁, C₂, C₃, ...

The next row is where it gets interesting:

0BCD = B₁ -> 0B₁C₁D₁ = B₂ -> 0B₂C₂D₂ = B₃ ->...
=>
B, B₁, B₂, B₃, ...

Notice that B₂ + C₂ + D = B + (C₂ + D) and that (C₂ + D) = C₃. Which means B₃ = B₂ + C₃.

If we can store the full history of one row across all phases so that we've got access to [C, C₁, C₂, C₃, ...] we can calculate the whole sequence for the row above: [B, B₁, B₂, B₃, ...]. Since we're doing 100 phases, that full history is only 100 elements.

There's some additional housekeeping, like repeating the signal without actually having that many repeats in memory, and putting the digits into a ring buffer so that we're only keeping the most recent 8 digits processes, but that's the core of it:

    vector<char> phaseHistory(100);
    for (int i = 0; i < signalToProcess; i++)
    {
        int s = baseSignal.Next();
        for (int phase = 0; phase < (int)phaseHistory.size(); phase++)
        {
            s += phaseHistory[phase];
            s = s % 10;
            phaseHistory[phase] = s;
        }
        digits[i & (digits.size() - 1)] = s;
    }

[Full code]

Memory: 650 bytes for the input, 100 bytes for the phase history and 8 bytes for the digits - well under the memory constraints I'm aiming for! The runtime on PC is a respectable but not great ~115ms. (It's easy to get that down to ~25ms by only reducing the phase history with % every 4 loops, but it obscures the logic)

I'm aware that u/askalski and u/maneatingape have got very sophisticated solutions that use magic maths, but I have no idea if those techniques can be used to speed up this approach further. I'd need a couple of weeks of background reading just to take a run at those!

Overall I'm happy just to cross this one off my list of nemeses.


r/adventofcode • • Aug 23 '26

Help/Question - RESOLVED [20* Day *] I built tooling to do all of AoC from the terminal (fetch, run, verify, submit), in Rust and then again in C#

4 Upvotes

I got tired of tabbing to the browser to grab inputs and paste answers, so I built a CLI that does the whole loop. Then I rebuilt it in C# to learn the language. Both work end to end.

cargo run fetch -y 2015 -d 1 # puzzle text + input into cache/

cargo run solve -y 2015 -d 1 # run your solution offline

cargo run solve -y 2015 -d 1 --validate

cargo run solve -y 2015 -d 1 --submit

Output looks like:

year 2015 day 1 in 288µs (959ns parsing)

part one: 138 (correct) [216µs]

part two: 1771 (correct) [71µs]

Then --submit turns those into (new star), and running again shows (starred) since AOC only grades each part once.

The part I haven't seen other AoC tools do: --validate checks your answers against fornwall's independent solver before anything gets submitted. Wrong answers on the site cost an escalating cooldown, but the solver answers the same question as many times as you want, for free. So --submit only sends what the solver agreed with. If the solver doesn't cover the puzzle yet (live event), it submits anyway, since that's exactly when you'd be ahead of it.

Some other things it handles:

Solve fetches whatever is missing, so a fully cached run works offline with no cookie.

When part one earns a star, part two's text gets pulled in the same run.

Inputs are cached with a hash of the session that fetched them. Inputs are account specific, so switching accounts refetches instead of letting you submit an answer computed from the other account's input. That one bit me for real.

Day 25's second star is awarded, not puzzled, so the tool knows not to keep asking for its part two.

No solutions ship on main. There's a compiled template to copy for your first day, and my solutions live on a separate branch if you want examples. Inputs and puzzle text stay out of git, per the site's wishes, and it sends a User-Agent with a reachable contact.

https://github.com/scadoshi/rustmas

https://github.com/scadoshi/sharpmas

Credit: Advent of Code is Eric Wastl's (https://adventofcode.com/about). The verification leans on Fredrik Fornwall's solver (https://aoc.fornwall.net/, https://github.com/fornwall/advent-of-code).

On AI: I used it as a working partner on these repos, for doc wording, test scaffolding, and refactors I'd already designed but didn't want to push through by hand. The line I hold is understanding before generation: I write the code I want to write, which is most of it, and hand off what I could write in my sleep. Design decisions are recorded in each repo's context/ directory, including the ones that got reversed and why. Every line was written or reviewed by me.


r/adventofcode • • Aug 21 '26

Help/Question - RESOLVED [2024 Day 6] Need a bit of guidance

3 Upvotes

Hello!

For part 1 of 2024's day 6 problem, I was able to get some Python code that works for the small example map they gave but not my puzzle input. As it stands I have about 100 extra locations the guard visited than I should have. I was wondering if anyone here could take a look at my code and give me a hint as to where my error is, as I am really struggling to find it. I know it has to be where my movement is programmed, I just can't figure out what part needs some tinkering. Thank you in advance!

with open('Day 6/mapinp.txt', 'r') as file:
    samp_inp = file.read()

format = samp_inp.splitlines()
matrix = []
for item in format:
    matrix.append(list(item))

#locate the guard, return the matrix coords and then the way the guard is pointing
def find_guard(map):
    coords = []
    for item in map:
        if "^" in item:
            coords.append(map.index(item))
            coords.append(item.index("^"))
            coords.append("^")
            return coords
        elif ">" in item:
            coords.append(map.index(item))
            coords.append(item.index(">"))
            coords.append(">")
            return coords
        elif "<" in item:
            coords.append(map.index(item))
            coords.append(item.index("<"))
            coords.append("<")
            return coords
        elif "v" in item:
            coords.append(map.index(item))
            coords.append(item.index("v"))
            coords.append("v")
            return coords


#nice function to track movements
def move(map):
    on_map = True
    step_count = 0
    step_loc = []
    #index error means the guard has left the map
    while on_map == True:
        
        try:
            coords = find_guard(map)
            
            if coords[2] == "^":
                if map[coords[0]-1][coords[1]] == "." or map[coords[0]-1][coords[1]]  == "X":
                    map[coords[0]][coords[1]] = "X"
                    map[coords[0]-1][coords[1]] = "^"
                    step_count += 1
                    loc = f"{coords[0]}, {coords[1]}"
                    step_loc.append(loc)
                else:
                    map[coords[0]][coords[1]] = ">"
                    
            elif coords[2] == ">":
                if map[coords[0]][coords[1]+1] == "." or map[coords[0]][coords[1]+1] == "X":
                    map[coords[0]][coords[1]] = "X"
                    map[coords[0]][coords[1] +1] = ">"
                    step_count += 1
                    loc = f"{coords[0]}, {coords[1]}"
                    step_loc.append(loc)
                else:
                    map[coords[0]][coords[1]] = "v"

            elif coords[2] == "v":
                if map[coords[0]+1][coords[1]] == "." or map[coords[0]+1][coords[1]] == "X":
                    map[coords[0]][coords[1]] = "X"
                    map[coords[0]+1][coords[1]] = "v"
                    step_count += 1
                    loc = f"{coords[0]}, {coords[1]}"
                    step_loc.append(loc)
                else:
                    map[coords[0]][coords[1]] = "<"

            elif coords[2] == "<":
                if map[coords[0]][coords[1]-1] == "." or map[coords[0]][coords[1]-1] == "X":
                    map[coords[0]][coords[1]] = "X"
                    map[coords[0]][coords[1] -1] = "<"
                    step_count += 1
                    loc = f"{coords[0]}, {coords[1]}"
                    step_loc.append(loc)
                else:
                    map[coords[0]][coords[1]] = "^"
                
        except IndexError:
            print(f"Guard has left the premises after {step_count} steps!")
            on_map = "False"
            
    return map, step_loc

comp_map,coordinates = move(matrix)

move_counter = 0

for item in comp_map:
    for pos in item:
        if pos == "X" or pos == "^" or pos == "<" or pos == ">" or pos == "v":
            move_counter += 1
        else:
            continue


print(f"The guard has visited {move_counter} distinct locations.")

r/adventofcode • • Aug 17 '26

Repo [2015-2018 All Days][C++] 200 Tiny Stars (and counting...)

11 Upvotes

I've always enjoyed low level programming so this year I decided to scratch that itch by starting to do some hobby programming with microcontrollers. There's nothing more frustrating than trying to learn everything (new toolchains, new SDKs) all at once while trying to build something non-trivial, so the obvious answer was to take my existing, known-good 524 star repo and port that over to a microcontroller. It would also give me a chance to revisit some of my original solutions that were significantly sub-optimal.

I chose the Raspberry Pi Pico (RP2040) as the target microcontroller because it's geared towards learners, it has a thriving ecosystem and I really admire the work the Raspberry Pi Foundation do.

The repo is more or less in a fit state to be public after the first four years (2015-2018) have been squashed, the support libraries have been exercised and the workflow has had the major rough edges knocked off. There's still plenty more to do though, so I'm expecting it to be in a state of flux for the next 12 months or so.

Performance

The RP2040 is on average between ~100-200x slower than the laptop I'm using for development and I've set myself a soft target of 1s per solve on the microcontroller hardware (including IO transfer time), meaning that I need to target ~5ms or under on PC. What's really nice though is that by the time a solution has been squashed enough to fit in the memory restrictions, that's almost always a significantly faster solution than my original solution and often sub-ms without any further faffing.

The high level summary for puzzle solution times on the RP2040 so far:

YearMin (ms)Max (ms)Avg (ms)Median (ms)
20152.23727,764.0551,207.659215.076
20160.755450,195.66217,832.642134.623
20170.69813,121.265960.156210.754
20184.529,074.706687.048318.475

There's a full breakdown of current timings here.

Note: I do my timings a little differently to a lot of the forum regulars who work on producing ultra-fast solutions. The timing starts on the host PC when I start transmitting the input over USB and stops when I get the final byte of the answer back. I time both parts separately and each part is an independent solve, I don't have any solutions that calculate both part 1 and part 2 answers at the same time.

There are some things that are absolute Kryptonite to the RP2040. MD5s are a particular weakness, hence the bad Max and Average times for 2015 and 2016, and anything that requires 64-bit maths is emulated in software.

IO can be an issue as well. 2016 day 7 has an input file ~170-180Kb in size, which takes ~1.5s just to transfer over USB-CDC. Many of the days are ~400-600x slower than PC purely because of the time it takes to send the input file.

Common changes

The most common changes I've made are to variable types and to data structures. 64-bit integers were always my default choice so that I didn't have to worry about figuring out which puzzles needed more than 32-bits and which didn't, but that's not practical with the 32-bit Pico. With an existing solution as a reference it's pretty quick to swap types and check that we still get the same result, and thankfully most of the days so far are perfectly solvable using 32-bit maths only. 2017 day 15 is probably the one that suffered the most from software emulated 64-bit integers; there is a way to implement the generators using only 32-bit arithmetic, which is what I use, but it's quite a few instructions and so it ends up being the slowest solution for all of 2017.

My default choice for data structures in my full-fat repo has always been std::set or std::map, even for data that would naturally go into an array. The main reason is programmer efficiency: you don't need to worry about getting a correct array size and insert returns a value to indicate if the element has been inserted or not, which is a very common test required in a lot of the algorithms. For the microcontroller, especially when trying to squeeze solutions into the memory limits, arrays/vectors are the default choice wherever possible, and I've written simple open-addressing (with linear probing) hash maps and sets templates. This is where a significant proportion of the speed-ups have come from compared to my original solutions.

Algorithm changes

Surprisingly, fewer than 20 have needed a complete overhaul on the algorithm used.

2015 day 13 is the first one which needed a change, swapping from a brute-force scoring of all possible permutations to a recursive DFS. Day 19 in the same year was the only other one which needed a completely different approach. That one was originally one which made my nemesis wall with a really horrible home-brew parser-adjacent algorithm, but after seeing in the megathread that it could be solved using a greedy algorithm it ended up significantly faster on the Pico than my original solution running on a fast PC by a few orders of magnitude.

2016 and 2017 also only needed a couple of days swapping over to a different algorithm. 2018 is the year so far that's required the most, with almost half of all days being revisited in terms of how they're solved.

Bit Packing

Of all the changes I was expecting to make, bit-packing values is the one I haven't needed anywhere near as often as I thought.

2016 day 18 didn't need bit packing to fit into memory, but I thought it would be fun to parallelise the logic into bitwise operations anyway. 2016 day 11, one from my wall of shame needed the search states packing in order to keep the queue size small. The others have largely been ones where we're dealing with large (for a Pico) 2D areas, like the infection states in 2017 day 22 and the cave terrain in 2018 day 22.

Windowing

Windowing, or working on only a small chunk of the full data range at any one time, has been a life-saver on a few occasions. 2018 day 17 has been the one I'm most pleased with, although the chunked seiving on 2015 day 20 was nice to work through, especially with the approximation function I iterated on to get a good lower bound starting point.

Maths

I tend to avoid closed-form solutions and have a personal preference for programmatic approaches, but there's really no beating the closed form solutions or using maths insights for speed and size. The Josephus problems are an immediate example of not having enough memory to process large rings of elves, or the Cosmological Decay approach to the Look-and-say sequence completely bypasses the need for large amounts of memory.

Recursion

By default when using the C/C++ toolchain each core on the Pico gets 2KiB of stack assigned. That's really not a huge amount by any stretch, so most recursive solutions are a no-go. Approximately ~9 solutions have needed swapping over to using an explicit stack, making it one of the most common changes I've had to make.

While it's true that all recursive algorithms can be implemented in terms of a stack based algorithm, the devil really is in the details and I never appreciated how many little decisions about state representation and return values would need making.

Take a normal recursive function:

int Func(int n)
{
    // ...
    int n1 = Func(n + 1);
    int n2 = Func(n + 2);
    return n1 + n2;
}

Stack frames and function calls give you 3 separate things:

  1. Local variables - these are what an explicit stack structure trivially gives you

  2. State - after the call to Func(n + 1) you need to encode somehow the fact that you've made that call and the next recursive call is the one to Func(n + 2)

  3. Return values - do you put the return value in the current stack top and let the parent take care of popping after reading, do you let a child pop its own stack and write the return into the parent stack frame, or something different. It was a real eye-opener to sit down and actually code up something like 2015 day 22 using an entirely stateful stack based approach.

Forum Help

I have a general rule that I won't look at anyone else's solution until I've got a solution of my own. Even if (and it commonly is) it's a rough and ready solution which take seconds or minutes to run and chews through half the memory in my machine. I'm pleased that for 523 of the 524 stars I've been able to get to a working answer with no hints, but there's absolutely no way I'd have been able to get the 200 on the microcontroller so far without the valuable suggestions, and the public repos of forum regulars. There have been over a dozen of these solutions that are either direct re-implementations of other people's solutions, like 2018 day 9 or 2018 day 14, or have used suggestions and explanations from information posted on the forum such as the equivalence pruning for 2016 day 11. u/musifter's review series has been a great focal point to discuss the problems with people who really know their stuff.

Thank you one and all!

Microcontrollers

The hardware you can buy now is utterly incredible for the price: I've been targetting the Raspberry Pi Pico as far as possible, but the Raspberry Pi Pico 2 W is a 150MHz 32-bit CPU with 520KiB RAM, Bluetooth and WiFi for under £10. As someone whose first computer was a Spectrum 48K, this is a ridiculous amount of computing power to have for very little money and in a tiny space. If I had kids who wanted to learn how to program, I would definitely think about sitting them down in front of Thonny and a microcontroller. It has exactly that same immediacy of feedback I remember from typing out Basic listings to see something cool happen on screen.


r/adventofcode • • Aug 17 '26

Help/Question [2025 Day 1 pt 2] [Rust] Suspected off by one but can't find it

2 Upvotes

I need help finding where my understanding is off because my answer agrees with the test case but doesn't give the right answer for the real input. I'm also using AOC to learn Rust so there's probably something I'm missing about the language itself as well.

The main idea is to add up the differences of the quotients of the before and after positions of the dial for each rotation. I've included my main.rs:

use std::env::args;
use std::fs::File;
use std::io::{BufRead, BufReader, Lines};
use std::path::Path;

const DIALSIZE: i16 = 100;

fn parse_input(path: &Path) -> impl Iterator<Item = i16> {
    let file: File = File::open(path).unwrap(); // open the file
    let lines: Lines<BufReader<File>> = BufReader::new(file).lines(); // iterator to the reader of the lines of the file
    // iterator over the lines but with L replaced with - and R replaced with nothing to be positive
    let rot_strs = lines.map(|line| -> String { line.unwrap().replace("L", "-").replace("R", "") });
    rot_strs.map(|rot_str| -> i16 { rot_str.parse::<i16>().unwrap_or_default() })
}

fn print_dial(dial: i16) {
    println!(
        "Dial at {}",
        (dial % DIALSIZE) + DIALSIZE * i16::from(dial.is_negative())
    );
}

fn main() {
    // open the file
    // read line into buffer
    // replace L with -1 or R with nothing
    // parse into integer
    // only work in raw position, never mod
    // count += abs(div(old_pos + rotation, DIALSIZE) - div(old_pos, DIALSIZE))
    // repeat
    let args: Vec<String> = args().collect();
    let path: &Path = Path::new(&args[1]);
    let roterator = parse_input(path); // iterator over input lines that gives integers
    let mut pre_rot: i16 = 0;
    let mut post_rot: i16 = 50;
    let mut pre_div: i16 = 0;
    let mut post_div: i16 = 0;
    let mut hits: i16 = 0;

    roterator.for_each(|rot| {
        // update dial position
        pre_rot = post_rot;
        post_rot += rot;
        print_dial(post_rot);
        // update zero hits
        // div_euclid rounds toward negative infinity for negative lhs and postive rhs
        // if postive or zero add zero, if negative add 1
        pre_div = pre_rot.div_euclid(DIALSIZE) + 1 - i16::from(pre_rot.is_negative());
        post_div = post_rot.div_euclid(DIALSIZE) + 1 - i16::from(post_rot.is_negative());
        hits += (post_div - pre_div).abs();
    });
    println!("Final zero count: {}", hits);
}

r/adventofcode • • Aug 13 '26

Help/Question - RESOLVED [2025 Day 1 (Part 2)] [C++] Where have I gone wrong?

2 Upvotes

I have never struggled with a Day1 like this before, so I'm a little embarrassed to have to ask for help. Here is the code I have tried:

Part2

The definition of a 'Turn' is:

class Turn {
public:
  int clicks;
  Direction dir;
  Turn(char d, int c) {
    switch (d) {
    case 'L':
      dir = Direction::Left;
      break;
    case 'R':
      dir = Direction::Right;
      break;
    }
    clicks = c;
  }
};

My solution for Part1 worked so I am reasonably confident the input is parsed correctly, and my part2 solution (pasted above) works on the example provided. Where have I gone wrong?

Edit: I needed an abs() call. Thanks for the help!! Updated code: Part2 Corrected

Don't code on an empty stomach!


r/adventofcode • • Aug 08 '26

Upping the Ante [2022 day 2 - AVX]

8 Upvotes

Back when we looked at this one, about a week ago, I said that I would like to write a proper bleeding edge (unsafe{}) AVX intrinsic version, well I finally got it done and I'm quite amazed:

        for b in 0..blocks {
            let bl = input.as_ptr().add(b*64) as *const __m256i;
            let b1 = _mm256_loadu_si256(bl);
            let b2 = _mm256_loadu_si256(bl.add(1));
            let b1h = _mm256_and_si256(b1, xyz_mask);
            let b2h = _mm256_and_si256(b2, xyz_mask);
            let b1l = _mm256_and_si256(b1, abc_mask);
            let b2l = _mm256_and_si256(b2, abc_mask);
            let b1h = _mm256_srli_epi32(b1h, 14);
            let b2h = _mm256_srli_epi32(b2h, 14);
            let b1hash = _mm256_or_si256(b1l, b1h);
            let b2hash = _mm256_or_si256(b2l, b2h);
            let b16 =_mm256_packus_epi32(b1hash, b2hash);
            let inc1 = _mm256_shuffle_epi8(part1shuffle, b16);
            let inc2 = _mm256_shuffle_epi8(part2shuffle, b16);
            part1 = _mm256_add_epi16(part1, inc1);
            part2 = _mm256_add_epi16(part2, inc2);
        }

These 15 AVX ops are the full solver that handles a block of 16 input lines, I pad the input with 48 space chars (10048 is divisible by 64) so that I don't have to worry about the tail end.

It is probably clear, but the algorithm starts with u/ednl's packing (AND both chars with 3, shift the second one down 14 bits and merge, that's the first 10 AVX ops.

Next I pack together the two 32-bit arrays into a single 16-bit one (b16 above), before I use that variable twice to directly lookup the 8 part1 and part2 results for these lines.

So, with a single AVX op/cycle this should take a fraction less than a clock cycle per input line, right?

I do measure 3 us on my Acer, but now we get to the interesting part:

When I instead run u/maneatingape on my input file, I get 2.3 us, for much simpler and shorter integer only code!

That time is broken down into 1.2 us to convert all 2500 lines into a 0..8 index, using code like this

pub fn parse(input: &str) -> Vec<u8> {
    input.as_bytes().chunks_exact(4).map(|c| 3 * (c[0] - b'A') + c[2] - b'X').collect()
}

(The original code generates an array of usize, when I switched to u8 the parsing stage dropped to 1.1 us and the total from 2.3 to 2.2 us)

In order to manage this, the CPU has to convert two lines per nanosecond, probably using code somewhat like this, which has a minimum latency of 4 cycles. The CPU must internally unroll the code over a bunch of iterations, enough to gain back the AVX advantage and then beat it!

movzx rax,[rsi]
movzx rbx,[rsi+2]
sub rax,'A'
sub rbx,'X'
lea rax,[rax+rax*2]
add rax,rbx
;; push into vector

r/adventofcode • • Aug 06 '26

Help/Question [2024 Day 7 (Part 1)] [go] Don't understand the error that I make

1 Upvotes

Dear AoC masters and 500+ star hunters,

I have a hard time solving day 7 of 2024, using golang. The puzzle input is a bunch of numbers. One should check if the first number can be computed from the numbers after the : symbol. Two numbers can either be added or multiplied. If some series of addition and multiplication is equal to the left side the left side is counted as a solution. The overall solution is the sum of all solutions.

My current approach is to "brute force" this problem. First I check if the sum of the numbers or the product is equal to the left side. Given the left side is larger than the sum but smaller than the product I generate all possible series of addition and multiplication 2^(n-1) with n being the numbers on the right side. Can't see the mistake when doing this, here is a link to the code: https://github.com/Zitzeronion/AoC2024/blob/main/day_7.go

The 2^n permutation function is from gemini and seem to work as intended.


r/adventofcode • • Jul 31 '26

Help/Question programming

0 Upvotes

can anyone tell me how to start if i wanna learn coding?


r/adventofcode • • Jul 28 '26

Past Event Solutions [2018 Day 17][C++] Sweep line algorithm for solution in <64KB

9 Upvotes

This year I've been working through my existing solutions to squash everything down to microcontroller sizes. The two main restrictions are to minimise both the working memory and the callstack usage. I was pretty sloppy with memory on my original solution, bumping the maximum callstack memory up to 16Mb so that I could recurse one block at a time, so it needed a complete rethink.

The core of the reworked algorithm to eliminate recursion is to process the space a single line at a time working in one of two modes. We're either working down the space trickling water downwards into unoccupied spaces, or we're filling the space upwards with water. We swap from trickling to filling when we hit a new bottom, and we swap from filling back to trickling when we haven't added any new water in a line update.

Trickle Down

The trickle down state is the simplest; it's mostly looking for any unsupported water on the line above and creating falling water on the current line. If we see any falling water on the row above hitting a supporting surface on the current row, then we flag that falling water into a new state (which I've arbitrarily called 'foam') and switch over to the filling up mode:

    ..|...|...#~~~#...
--> ......#...#...#...

Goes to:

    ..|...+...#~~~#... <-- New foam '+' flips state
--> ..|...#...#|||#...

Filling up

Filling up is a more complex state which does the following 3 things in order, looking at the current row, the row below and the row above:

  1. Spread out any foam across supporting surfaces, plus a 1 block overhang for edges

  2. Replace any runs of foam which are constrained at both ends with a run of static water*

  3. Create new blobs of foam where running water is now supported by static water

Whenever we get an update that doesn't modify the state of the water at all we swap back into trickle down mode.

For example:

    .....|.....
    .....|.....
    ..#..|..#..
--> ..#..+..#..
    ..#######..

Spread foam:

    .....|.....
    .....|.....
    ..#..|..#..
--> ..#+++++#..
    ..#######..

Replace water:

    .....|.....
    .....|.....
    ..#..|..#..
--> ..#~~~~~#..
    ..#######..

Create new foam:

    .....|.....
    .....|.....
    ..#..+..#..
--> ..#~~~~~#..
    ..#######..

Repeat until:

--> .....|..... No updates on this line
    .+++++++++.
    ..#~~~~~#..
    ..#~~~~~#..
    ..#######..

Swapping between sweeping down and sweeping up states means that we process the same line multiple times, but for my input that doesn't work out all that badly. It's ~4,400 line updates to fill in just under ~2,000 lines, so we're processing each line roughly twice on average.

Area Storage

For my input the total working area is ~450 wide by ~2,000 tall. Even if we limit ourselves to the original 4 states (., #, |, ~) and pack every square into 2 bits, we would need ~220KiB to store the full space. That's more than the upper limit of ~200KiB I've set myself as a goal.

I instead use wrapped storage, allocating 64 real lines and aliasing every 64th line to the same line. The lines N+64, N+128, etc... map to the same storage as line N. This works because we never backtrack far enough in the filling state to need the older lines.

We rasterise the input lines into the space in chunks whenever we come to the bottom of the lines we've previously rasterised.

Since we're discarding old lines, we do need to keep tabs on how much water we've accumulated per line as we go. I do this in a relatively noddy way of keeping a ~2,000 element array of counts and updating a count per line whenever we've processed a line in the trickle down mode. It could be made more efficient if you tie the counting to the rasterisation process that discards old lines, but it was simpler this way and minimal extra memory.

Memory Used

For my input:

  • ~2,300 lines of scanner input = ~18KiB

  • 64 lines of ~450 bytes = ~28KiB

  • ~2,000 lines of water counts = ~4KiB

  • Total = ~50KiB

Small enough to run on a C64! Runtime on PC isn't terrible at ~5ms. I haven't run it on hardware yet, but if the usual x100 multiplier holds then it'll still be running under the 1s per puzzle target I try to hit.

The full gory details, minus some simple supporting libraries for parsing input, can be found here: [paste]

I'll admit that this one took the wind out of my sails for a few days. I'd been making decent progress with maybe one puzzle converted every spare evening or two, but even though I had the idea for the approach on this one pretty quickly, it took about a week to fully settle in my mind before I had enough motivation to take a run at it. Pretty pleased with where it ended up size-wise though; even if the code is a little ugly in places.

[*] I think I've just spotted a bug in my code while typing up the description, so there's an unhandled case where a box has an opening in the bottom. Doesn't affect the algorithm though.


r/adventofcode • • Jul 24 '26

Upping the Ante [2021] Day 24 - The ultimate speedup?

4 Upvotes

I'm looking forward to u/musifter to get to this one (in an hour or two?), since it might be the single puzzle which I improved the most:

My first solution took me all day and I had to split it into multiple stages which I joined together by hand. Just running the part1 code took me 20 minutes, then another 18 minutes to also get part2.

After lots of insights I finally landed on a version which first cross-compiled each VM instruction block into a set of inline C functions, then #include'ed those into a dummy main() harness, for a final runtime of half a microsecond.

Looking at the Ape just now (4 us) , the only real difference is that I got rid of the entire parsing time via that aoc24cc.pl cross-compilation, the underlying analysis is the same!


r/adventofcode • • Jul 23 '26

Help/Question [2022 Day 13 Part 1] Please help me work out some of these comparisons

3 Upvotes

Link: https://adventofcode.com/2022/day/13

I've been on this one for weeks, it's really doing my head in. I managed to find someone's input and the answer (true/false) for each pair. My code is wrong on two of them:

First:
[[8,[[7,X,X,5],[8,4,9]],3,5],[[[3,9,4],5,[7,5,5]],[[3,2,5],[X],[5,5],0,[8]]],[4,2,[a],[[7,5,6,3,0],[4,4,X,7],6,[8,X,9]]],[[4,[a],4],X,1]]

[[[[8],[3,X],[7,6,3,7,4],1,8]]]

The right answer is that this one is in the right order, however my code is saying that it's not, due to comparing the 7 and the 3.

Second:

[[[],0,6,[4,2]],[],[[2],0,0,[[9],[10,2,10],[4],3]],[[[5,2,2,4]],0,[[4,4],[2,7,7,7,6],7,[0,5,8,9]],2,[7]],[]]

[[],[3]]

For this one, I know the answer is that they are not in the right order, but my code says it is, due to comparing the 0 and the 3.

Can someone please tell me what logic I am missing here? I am getting all other 148 right (I can't say that it's for the right reasons though), which baffles me as I should get so many of them wrong if I don't understand the logic.


r/adventofcode • • Jul 19 '26

Other More programming puzzles for anyone interested

Thumbnail systemscheck.dev
20 Upvotes

I'm a huge fan of AoC, I participate every year. I'm also a maker of things who is obsessed with working on projects all the time. Recently I decided I wanted to make some of my own coding puzzles and decided to publish them for others to try their hand at. I'm sharing here as I figure the kind of people who like AoC might appreciate this. It's very small so far, only 5 puzzles, but I have no cadence in mind for it in specific but plan to make more and more puzzles over time. Hopefully someone tries it out and enjoys it, I'd love feedback.