r/adventofcode • • Oct 09 '26

Other [2024 Day 10] In Review (Hoof It)

5 Upvotes

Today we are going to help a reindeer reconstruct the hiking trail map of an area recently scoured by lava. We have a digital height map (0 to 9) and are told to, for all starting points (elevation 0) find out how many peaks (elev. 9) can be reached from that point while always climbing exactly one level per step.

The total peaks sum is the part1 answer.

Solving this reminded me a lot of several previous map search puzzles, so I did it the obvious way: Use the input as a linear flat map, with newlines as a guard between each horizontal line and the next. I also put a line of guard characters before and after the input.

Next was a scan of the input map, for each '0' start a recursive DFS, using a parallel seen[] array to note visited cells, then just aggregate the counts.

In hindsight, it would probably be better to cache the search results from each visited cell, so that later searches could reuse the work previously done.

For part2 we are instead told to count how many different ways there are to reach a top, here I also used a recursive search, but totally forgot to make it memoizing!

Adding just two lines just now to return early with a cached answer, otherwise do the search and cache the result made my code more than twice as fast. The only reason it wasn't even larger was because every path had to be just/exactly 8 steps long, with very limited fanout, so the total overhead wasn't anything like previous search puzzles where a cache could very often save 95-99% of the work.


r/adventofcode • • Oct 08 '26

Other [2024 Day 9] In Review (Disk Fragmenter)

6 Upvotes

Today an amphipod has a classic problem: It has a disk that is fragmented and it wants to defragment it.

The disk map is stored in a compressed format, alternating between a file length and a free space length. If there is no free space between two files, the free space length is 0.

For Part1, the amphipod moves blocks, starting with the last file block which it then moves into the first free block, systematically moving all blocks as close to the front as possible, and as a side effect reversing the storage order for all moved files. We then produce a disk checksum consisting of summing up for every file block the product of the file number and the block position.

For Part2, because the amphipod realized that the disk becomes too fragmented, it will instead only move full files as close to the front as it can find a large enough free space for them. The checksum is then calculated in the same way as Part1.

My Perl code solved this one using brute force for Part1:

First expand the run length encodings, using -1 to designate free blocks, the filenr ID for the files. My input contained 10K files, so worst case this could be expanded to an array with 9*2*10K = 180 K entries, but the average should be closer to half of this.

This setup made part1 really easy, just iterate from the front to locate free blocks and from the end to find file blocks to move.

For part2 we need to find open gaps large enough for a full file, so here it made much more sense to have free lists, either organized by size (1-9) and location, or just by location. Since all partially filled free spaces would result in a tail space which would have to be inserted in the right order in the smaller map I decided to use the simpler setup of a single free list.

I thought about keeping a cache of the last found free list entry of each size, but went brute force instead, always scanning from the beginning. I counted the scan iterations, the average was 133 entries inspected before finding a large enough slot, so a better data structure would have been faster.

Perl runtime was 271 ms on my slow Surface.

I started on a more ambitious Rust version but never had time to finish it the way I would have liked.

It would in fact have been easier to solve the defragmentation problem in an optimal way, using size-ordered free lists and always try to move files to an exactly large enough gap, only fall back to larger slots if none could be found.

Later edit:

Watching TV with my wife ("71 degree North", check it out if you can!) and waiting until Oslo midnight to make the reddit post, I looked somewhat unhappily at what I had written above:

I decided to at least implement the simplest possible cache I mentioned, just a table of the last found free entry for each size, this immediately dropped the runtime to 47.8 ms, so nearly 6x faster!

The number of free list steps dropped from 133 to 4.6 per file.

The only small problem was that I had to update the cache also for the tail end of a partially filled free space, when that was before the current cache entry.

    if ($flen >= $len) {
        my $remfree = $flen - $len;
        $free[$f] = $remfree;
        $free[$f+1] += $len;    # update free block position
        $files[$i+2] = $fpos;   # The file is moved here
        $lastfree[$len] = $f+2; # Next scan starts after this entry
        
        if ($remfree && $lastfree[$remfree] > $f) { $lastfree[$remfree] = $f; }
        last;
    }

Note that my lastfree[] array has entries for 0..9, so that I could blindly update it also for totally filled slots, but it was a percent or two faster to check for this situation and skip the zero updates.


r/adventofcode • • Oct 07 '26

Help/Question - RESOLVED [2021 Day 3 (Part 1)] i want to understand the puzzle

4 Upvotes

Each bit in the gamma rate can be determined by finding the most common bit in the corresponding position of all numbers in the diagnostic report.

what do they mean finding the most common bit in the corresponding position? what's the corresponding position? I thought at first that the most common bit is how many 1's or 0's there is in the binary number, but it's not, I couldn't find the pattern here plus my native language is not english

edit: okay now i get it, thanks for the replies!


r/adventofcode • • Oct 07 '26

Other [2024 Day 8] In Review (Resonant Collinearity)

7 Upvotes

We're on the roof of the top-secret Easter Bunny installation, where we realize that the city contains a bunch of antennas, at many different frequencies. They are named with single digits, upper or lower-case letters, so there can be up to 62 different kinds.

For Part1 we are told to look for antinodes, defined as a location that are in line with a pair of same-frequency antennas, at the same distance away as the internal pair offset. We want to determine how many total locations contain one or more anti-nodes.

In Perl I created a hash of arrays, the hash is keyed by the antenna name (ascii byte value), this points to an array which contains the (x,y) coordinates of every antenna with that name. The list of anti-nodes was another hash table, keyed by the corresponding (x,y) pair. The main issue is that we have to ignore any locations that are outside of the city grid.

This worked pretty much as quickly as I could type it in.

For Part2 we need to iterate over all multiples of the internal distance, so we get a lot more antinodes, but otherwise it was more or less the same process. The only possible wrinkle was that if an offset between two antennas (dx,dy) has a common divisor, then we must get rid of that so I had to write a gcd() function to fix this even though it seems like it never actually happened?

Total Perl runtime 16 ms.

In Rust I first implemented it the same way, using HashSet, but later on decided that the name key set was small enough that it didn't matter if I extended it by filling in the gaps between '9' and 'A' and between 'Z' and 'a', and instead of a HashSet of antinode addresses I just used a linear byte array, using bit 1 for Part1 and 2 for Part2 locations.

When I ran my code just now the fastest was 3.9 us, so I'll have to average 1000 iterations to get a more precise measurement:

...

The average over 1000 iterations was 3519 ns, so less than half the 8 us shown by u/maneatingape.

I therefore tested 'cargo bench year2024::day08' and got

running 3 tests
test year2024::day08::parse_bench ... bench:       3,745.39 ns/iter (+/- 247.27)
test year2024::day08::part1_bench ... bench:         724.87 ns/iter (+/- 29.24)
test year2024::day08::part2_bench ... bench:       1,375.97 ns/iter (+/- 94.11)

So his total was about 5.8 us on my machine, not a very big but still somewhat significant difference.


r/adventofcode • • Oct 06 '26

Other [2024 Day 7] In Review (Bridge Repair)

4 Upvotes

Today we need to cross a bridge which is currently under repair, only the final calibrations remain, but the engineers have a problem: Each calibration consist of a target value and a computation which is supposed to reach that value. A group of nearby elephants have stolen all the operators so that only the numbers remain, our task is to figure out where we can insert '*' (multiplication) or '+' (addition) between the numbers to make it come out OK.

These equations ignore normal operator precedence rules, both are at the same level and will be applied as soon as possible.

In the test data set the number of values is so low that it seems OK to just try all combinations, in the real input we find up to 12-14 numbers but we would still only need to test 4096-16384 possibilities.

However, it is immediately clear that if the last operator is a multiplication, then the target value must be divisible by the last number. Otherwise it must be an addition, so then we can just subtract that value from the target and retry with the remaining set.

The obvious choice is therefore a recursive descent where we for each level first test if multiplication works, if so divide and recurse down, otherwise subtract and recurse.

This process finished in a ms or two in Perl.

For Part2 we are told that one elephant had hidden away a third operator, concatenation!

At this point all Perl programmers rejoiced since for Perl any number is both a string and a numeric value, so that checking if the last N digits match an N-digit value is dead simple, and so is removing the corresponding digits from the current target so that we can recurse.

My Rust code started out with the exact same logic, converting numbers to ascii and back for each concatenation attempt, and it took about twice as long as the Ape, even though I started with a sanity check: For concatenation to be possible, the last digits had to match so I checked this before doing the string conversion and comparison.

After I had stared at this logic for a while I realized that I could repeat the final digit check until it either stopped matching or all digits were OK, at which point the temporary target would contain the remaining leading digits, without any need for any binary-to-ascii and ascii-to-binary conversions!

At this point the inner logic was quite short & nice, it ran in 163 us:

fn try_part2(target:u64, nums:&Vec<u64>, pos:usize) -> bool
{
    if pos == 0 {return false;}
    let pos = pos - 1;
    let n = nums[pos];
    if pos == 0 { return n == target; }

    if target % n == 0 {
        let rem = target / n;
        if try_part2(rem, nums, pos) {return true;}
    }
    let mut n2s = n;
    let mut t2s = target;
    while n2s > 0 && n2s % 10 == t2s % 10 {
        n2s /= 10;
        t2s /= 10;
    }
    if n2s == 0 {
        if try_part2(t2s, nums, pos) {return true;}
    }

    let diff = target - n;
    try_part2(diff, nums, pos)
}

I guessed that u/maneatingape should have very similar logic, his time of 136 us on an Apple CPU could easily be explained by the optimized divider circuit in later Apple cores, but when I tested with cargo bench year2024::day07 I got 133 us on my Intel CPU, so he is still a fraction more efficient!

I am using the standard library to split the input into lines, I then parse each line with an extract_u64() function. When I tried to go hardcore with a full custom input parser, it turned out to be significantly slower.


r/adventofcode • • Oct 05 '26

Other [2024 Day 6] In Review (Guard Gallivant)

7 Upvotes

The task for the day is to search a rectangular area (130x130 cells in my input) of a lab where a single guard is patrolling. Since there are no walls around this area, the guard will leave (and then randomly return presumably?) if her walk hits one of the edges. Before this happens, she always walks in a straight line until she hits an obstacle, whereupon she will turn right and keep going.

For Part1 we just need to simulate this process in order to count how many unique cells she will have visited before leaving.

Direct step-by-step simulation was the obvious choice, and afaik probably also the most efficient, except when walking in a horizontal direction where a language like Perl provides index/rindex, but I did not bother, just brute forced it to get the first star.

For Rust, C(++) and other low-level languages, direct simulation is a reasonable choice, so that's what I used here, recording in each cell that it had been visited with a bit per direction of travel.

For Part2 we want to introduce a single extra obstacle in the path the guard is about to walk, placed in such a spot that her path will turn into an infinite loop. I recorded the path taken in Part1, so for Part2 I just iterated over this path, checking what would happen for each possible choice. I could not see any obvious ways to short-circuit this search.

I first had the good idea (NOT) to think that any choice had to be placed just after a point where the guard had previously passed going right. Such a location would indeed work, but not if the real solution depends on hitting one or more previously unhit obstacles before starting the loop. Since we need to determine all possible locations, this means that part2 is going to require far more work than Part1, but we are all used to that at this point.

My main problem is that u/maneatingape is about an order of magnitude faster, so I must in fact have missed at least one huge optimization here!

Perhaps it makes sense to backtrack from each turn taken by the guard and check if a reverse path will hit a point previously visited, such that a right turn there would start the loop?

There are far less turns than steps in the Part1 path, so this should be faster!


r/adventofcode • • Oct 04 '26

Other [2024 Day 5] In Review (Print Queue)

5 Upvotes

The story this day is that we need to print a bunch of manuals, all consisting of a small number of pages from a master list, but there are also lots of rules about the printing order between pairs of pages, stating that if <N> and <M> are part of the same manual, N must always be printed before M.

Before the list of manuals to print we have a long list of these rules.

We know that for any given manual with its list of pages, these rules lead to a single unique legal ordering.

However, it is both possible according to the rules, and as far I know, also true that:

There exist at least one ring of rules (A<B, B<C,...X<Y,Y<Z, Z<A), which means that there cannot be any complete ordering of all the pages, so the order has to be determined for each set of manual pages, otherwise we could just have sorted the page numbers once and be done with it.

In Perl it felt natural to store these rules as hashes, each possible page number from 1 to 99 gets a list of the pages it must be before or after.

The code ran in 5.5 ms so fast enough for an interpreted language.

In my Rust version I noticed that 100 pages is less than 128 so I stored those lists as u128 bitmaps, this allowed all the checks to be done with logic AND operations.

For Part1 just iterate over the pages:

    fn is_ordered(&self, pagelist:&Vec<u8>) -> bool {
        let mut prev = pagelist[0];
        for p in 1..pagelist.len() {
            let curr = pagelist[p];
            if self.pages[prev as usize].infront & (1 << curr) != 0 {
                return false;
            }
            prev = curr;
        }
        true

If there is no rule for prev vs curr then that implies any ordering is OK for that pair of pages.

Part2 is a little bit (grin) more complicated, but the same bitmap logic determines which page must be first, second, third etc.

I start by generating a pagelist bitmap, with 1 bits for each page in that particular list, then I iterate over the pages, from the end forwards, until I find a page that has no other pages behind it (i.e., its "behind" bitmap ANDed with the pagelist bitmap is zero).

This page can then be exchanged with the original last page. After placing it, I remove it from the pagelist bitmap, step forward one position and repeat the process until all pages are ordered.

Total runtime was 10.867 us (average over 1000 runs) vs the 18 us given by u/maneatingape, so more than fast enough for me.

(While writing this I realized that I only needed one of the two bitmaps per page, that would have saved a little bit of the setup time, as well as 1600 bytes of memory, but since the total working set is less than 4kB, everything fits easily in $L1 cache.

I thought this was an interesting puzzle, with some similarities to classic problems like managing free space in a file system using bitmaps.

PS. I am posting this just before 0100 Oslo time on Oct 5th, I'll keep the tradition going as long as I can or until u/musifter returns!


r/adventofcode • • Oct 04 '26

Other [2024 Day 4] In Review (Ceres Search)

5 Upvotes

Next stop is the Ceres monitoring station, where instead of shooting asteroids, we're asked to help with a word search. In this case it's to find all occurrences of XMAS in an 140x140 grid. For part 2, we find out that we misunderstood the instructions, and want all the X-MASes (MAS that form an X).

For part 1, I didn't do anything fancy. I coded the standard word search algorithm of scan for the first letter, than scan outward from there to see if there are any matches. You do need to check them all, an X can start multiple XMAS in different directions... as the description says, "overlapping other words" is fine (one of my Xs has 5).

For part 2, I got a little bit fancier. I scanned looking for As (the middle of the X). Then grab the corners and check that the ones opposite are different (and M or S). Which is an XOR thing, and so:

my @Grid = map { chomp; y/MS/01/; [split(//), '~'] } <>;

...

for (my $y = 0; $y < $#Grid; $y++) {
    SQUARE:
    for (my $x = 0; $x < $#Grid; $x++) {
        my $coord = V($y,$x);
        next SQUARE if (&grid_at($coord) ne 'A');

        my @corners = map {int} grep {/[01]/} map {&grid_at($coord + $_)} @Diag;
        next SQUARE if (@corners < 4);

        $part2 += ($corners[0] ^ $corners[1]) & ($corners[2] ^ $corners[3]);
    }
}

Using the Vector module again. What I do is translate M and S into 0 and 1 when reading in the grid. When I get an A, I grab the diagonal corners that are 0 or 1, if I get a full set of four, I apply XOR to test that we have proper MAS/SAM and not SAS/MAM. The implementation is a bit hacked together, but it expressed the basic idea I had of using XOR (call it Art). My Smalltalk solution just did the testing with the letters:

part1 := ((grid selectPoints: [:chr | chr == $X])
                collect: [:pt |
                    TextGrid dirs count: [:d |
                        (1 to: 3) conform: [:i | (grid at: (d * i + pt)) == ('MAS' at: i)]
                    ].
                ]
         ) sum.

part2 := (grid selectPoints: [:chr | chr == $A])
               count: [:pt |
                   corners := TextGrid diags collect: [:d | grid at: pt + d].

                   (corners conform: [:c | (c == $M) or: [c == $S]])
                     & (corners first  ~= corners fourth)
                     & (corners second ~= corners third)
               ].

Of course dc doesn't have bitwise operators like XOR, so I needed to do something else to keep the streak up (in 2024, in the first 14 days, I did dc solutions for at least one part... except for day 12). And that came from converting the entire grid into numbers (1-4) so that dc could understand it (as 140-digit bignums). The M and S are 2 and 4 respectively, so the test is to multiply opposite corners and see if it's 8 (because that's unique, except for symmetry, and backwards is fine in word search).

tr 'XMAS' '1234' <input | dc -e'?dZdsn2+r[[A~3Rd3Rr:g1+rd0<?]ds?x1++?z1<L]dsLx[q]sQ[r2[_3Rrd3R+d;g4Rd3R!=Q1+d5>+]ds+x5/ls+ss+s.]sD[d_1lDxd1lDx2[dln+d_1*4Rd3RlDxd3RlDxr1-d_1<I]dsIxs.]sS[d;g1=S1-d0<M]dsMxlsp'

tr 'XMAS' '1234' <input | dc -e'?dZdsn2+r[[A~3Rd3Rr:g1+rd0<?]ds?x1++?z1<L]dsLx[ls1+ss]sP[dln-;grdln+;g3R*8=P]s/[dln2+-;grdln2++;g3R*8=/]s\[d;g3=\1-d0<M]dsMxlsp'

And so, this will be my last post for a while. I still don't know when I'll be able to do daily posts... u/terje_wiig_mathisen has offered to do the next few days, so we'll at least have continuity for a while longer (and day 5 was pretty fun day with its "topological" sort).


r/adventofcode • • Oct 03 '26

Other Autumn Code walk (another AoC clone)

11 Upvotes

Hello!

My pet-project is finally coming: Autumn Code Walk. It is a collection of coding challenges, not unlike AoC. It consists of 5 Problems and the first problem will be published next Monday (October 5th, 2026) at 6am CEST, then a new problem is published every 24hrs until Friday.

The website is purely client based so there is no login mechanism. However, localStorage is utilized for convenience and personalized experience. Statistics for correct solutions across users uses are gathered using an open-source api for tracking hits (don't abuse pls). Feel free to contact me if you find a bug or have a recommendation.

ACW can be found at: https://autumncodewalk.github.io/

Good luck and have fun!


r/adventofcode • • Oct 03 '26

Help/Question - RESOLVED [2022 Day 3 (Part 1)] [Lua] there isn't a better way to do this?

1 Upvotes

so the only thing i need is convert the item types to priorities. is there a better way to do this without making a big ol' if statement?


r/adventofcode • • Oct 02 '26

Other [2024 Day 2] In Review (Red-Nosed Reports)

7 Upvotes

First stop in our search is the nuclear plant where we made medicine for Rudolph in 2015. While the Historians search for their Chief, we agree to help analyze some data for the engineers.

And so we get another problem that just deals with numbers. The input has 1000 lines, each is a report which is a list of 5-8 numbers in the [1,99] range. A safe report is one which is monotone increasing or decreasing, and adjacent levels differ in the range of 1 to 3. For part 2, we discover that they have a Problem Dampener, that tolerates a single bad level.

Since I wasn't feeling well, I just brute forced this. Took the diffs and:

$part1++ if (all { abs($_) <= 3 && ($diffs[0] * $_) > 0 } @diffs);

For part 2, if this fails, I try splicing out each number in turn until one works (on not). I remember thinking a little bit about trying to spot the problem on the go... and it went like: if I get to the third number and discover there's a problem, the first or second could still be the problem to remove. And with these short lists, 3 items is a huge portion of it. So simpler to just go with programmer efficiency and test them one at a time. If things were longer it'd make more sense to get into doing things smart.

One interesting thing to note with the solution above is the use of arithmetic logic. I was already thinking of how to do this in dc. And so the trick in there to tell if things are monotone increasing or decreasing... I multiply each diff with the first. If that's always positive, things are monotone (ie all diffs have the same sign as the first one).

A side effect of this type of arithmetic logic is needing to consider the 0 value. And here we see it used to handle a case that appears at first glance to be missing... the check that the difference is at least 1. A difference of 0 fails the second multiplication test, and so that check actually handles 1Β½ of the rules.

In any case, the dc ended up as:

dc -e'[0*]sZ[1+]sC0?z[2-dsn[3Rd4R-Sdr1-d0<I]dsIx*ld+sa0ln[rLddd*v3<Zla*0<Cr1-d0<I]dsIx+ln/+?zd1<M]dsMxrp' <input

The combining of the two rules is done by conditionally multiplying difference >3 by 0, making that 0 in the second part of the test cover both parts. Another little trick in this one was that it keeps a count of the number of steps that pass and then divides it by the number of steps... a simple way to check that they're equal and get a 1 or 0 to add to the total for the answer (as we're working with 0 precision). And, whereas yesterday, the use of ? wasn't really that important to tell things apart, here each line has a different number of numbers... and being able to read the input one line at a time is useful without having to add delimiters to the input (although 0 is conveniently available for that).

And so for a problem I basically brute forced, I did do some interesting stuff in my solutions.


r/adventofcode • • Sep 30 '26

Help/Question [2024 Day 17 (Part 2)] [CUDA] Trying to brute force part two

1 Upvotes

Hello, I have tried to brute force part 2 of day 17 using cuda.

I am very new to cuda and this is what i have come up with. After 3.684722 days, the program outputs nothing and stops. The program works correctly on the sample data.

code:

#include <cstdlib>
#include <cstdint>
#include <cstdio>
#include <unistd.h>

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess)
   {
      fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}

__device__ uintmax_t do_combo(uintmax_t i, uintmax_t A, uintmax_t B, uintmax_t C){
        switch(i) {
                case 0:
                case 1:
                case 2:
                case 3: return i;
                case 4: return A;
                case 5: return B;
                case 6: return C;
        }
        return i;
};


__global__ void cuda(){

        enum instructions_names {
                adv,
                bxl,
                bst,
                jnz,
                bxc,
                out,
                bdv,
                cdv
        };

        uintmax_t instructions[16] = {2,4,1,7,7,5,0,3,4,0,1,7,5,5,3,0};
        uintmax_t i_len = 16;
        /* uintmax_t instructions[6] = {0,3,5,4,3,0}; */
        /* uintmax_t i_len = 6; */
        uintmax_t output[16];
        uintmax_t output_len = 0;
        /* uintmax_t step = 100000000*(blockIdx.x * blockDim.x + threadIdx.x); */
        /* uintmax_t stop = step + 100000000; */
        uintmax_t step = 10000*(blockIdx.x * blockDim.x + threadIdx.x);
        uintmax_t stop = step + 10000;
        for (;step < stop; step++) {
                /* printf("%lu ", step); */
                output_len = 0;
                uintmax_t A = step;
                uintmax_t B = 0;
                uintmax_t C = 0;
                for (uintmax_t i = 0; i < i_len; i+=2) {
                        if (output_len > i_len) break;
                        switch (instructions[i]) {
                                case adv: {
                                                  /* takes combo operand, divides A by 2^it into B */
                                                  A = A >> do_combo(instructions[i+1], A, B, C);
                                                  continue;
                                          }
                                case bxl: {
                                                  /* takes literal operand, XORs B and it into B */
                                                  B = B ^ instructions[i+1];
                                                  continue;
                                          }
                                case bst: {
                                                  /* takes combo operand, modulo 8 into B */
                                                  B = do_combo(instructions[i+1], A, B, C) % 8;
                                                  continue;
                                          }
                                case jnz: {
                                                  /* takes literal operand, jumps to it if non null */
                                                  if (A == 0) continue;
                                                  i = instructions[i+1] - 2;
                                                  continue;
                                          }
                                case bxc: {
                                                  /* ignores operand, XOR B and C into B */
                                                  B = B ^ C;
                                                  continue;
                                          }
                                case out: {
                                                  /* takes combo operand, outputs it modulo 8 */
                                                  output[output_len++] = do_combo(instructions[i+1], A, B, C) % 8;
                                                  continue;
                                          }
                                case bdv: {
                                                  /* takes combo operand, divides A by 2^it into B */
                                                  B = A >> do_combo(instructions[i+1], A, B, C);
                                                  continue;
                                          }
                                case cdv: {
                                                  /* takes combo operand, divides A by 2^it into C */
                                                  C = A >> do_combo(instructions[i+1], A, B, C);
                                                  continue;
                                          }
                        }
                }
                if (i_len != output_len) {
                        continue;
                }
                bool is_same = true;
                for (uintmax_t i = 0; i < i_len && is_same; i++) {
                        if (instructions[i] != output[i]) {
                                is_same = false;
                        }
                }
                if (!is_same) {
                        continue;
                }
                printf("%lu\n", step);
                asm("trap;");
        }
}

int main(){
        unsigned int threads = 1024;
        unsigned int all = 20000000000/threads;
        cuda<<<all,threads>>>();
        gpuErrchk( cudaPeekAtLastError() );
        gpuErrchk( cudaDeviceSynchronize() );
}

r/adventofcode • • Sep 20 '26

Past Event Solutions [2025 Day 9 (Part 2)] [elisp] Revisiting solutions in (e)lisp

3 Upvotes

I am revisiting my 2025 solutions, rewriting in elisp.

My original Python solution was horrible, so inspired by other solutions online, I did one using coordinate compression and pre-calculated "2D prefix sum".

The solution is rather long for an AOC solution (around 150 lines). I was therefore wondering if anyone has found a short general solution.

My elisp Solution


r/adventofcode • • Sep 19 '26

Other [2023 Day 19] In Review (Aplenty)

6 Upvotes

The Elves thank us and give us the hang glider they've found and we "borrowed" to get up here, so we can return it. At the bottom of the parts-fall we find Elves sorting them with an unusual system based on how extremely cool, musical, aerodynamic, and shiny they are. There's a big list of workflows with conditional rules to follow that will either direct a part to another workflow or (ultimately) accept or reject it. Naturally, we're here to help.

The input is two sections. Section #1 contains a little less than 600 workflows in my input... other than the start state of 'in', the workflow names contain no vowels (including y and w). Section #2 is the stats for 200 parts.

The workflow is essentially a big state machine... you can think of the workflows as multiple states if you want to think of it in a more formal/simple way:

px{a<2006:qkq,m>2090:A,rfg}

          a>=2006        m<=2090
      px0 --------> px1 ---------> rfg0
       |             |
a<2006 |      m>2090 |
       v             v
      qkq0        ACCEPT

That's not really needed in the code though. That's more of conforming things to more standard FSMs. But for part 2, that visualization was useful for me.

I did my normal approaches here... a quick solution to see part 2, where I turned codelike stuff into actual code to evaluate, and just followed the rules.

FLOW:
while ($flow ne 'A' and $flow ne 'R') {
    foreach my $rule ($Rules{$flow}->@*) {
        my $result = eval( $rule ) // '';
        if ($result) {
            $flow = $result;
            next FLOW;
        }
    }
}

Part 2 tasks us with finding the set of valid ranges that the rules accept. This is very much like day 5... we have 4 ranges instead of 1 (but only on [1,4000], but 40004 is much larger than 232 ) and in day 5, the order of the rules tables was fixed. So unlike day 5 where I iterated over the tables, here I went to recursion (the simple way to nest iterations an arbitrary number of times).

One nice thing about this problem in comparison to day 5, is that the ranges all go from the middle to the edge. So there's only one valid range for any variable at a time (you can't have anything accepted with x < 1000 and x > 3000). And so the basic idea was that after calculating what the intersection of the rule is with the current success range, we recurse to the next state if that's valid (ie doesn't have negative length) with that category set to the new success range. Otherwise we just proceed to set the range for that variable to the fail range (because we must fail), and iterate to the next substate in the diagram. The last arrow on the right is just a forced recursion for the non-conditional rules.

Part 2 for this one did take me a while to actually get right. In the end, I really think that drawing diagrams like the above are what helped finally get it right. It was probably good that there was a warm up with day 5 for this.


r/adventofcode • • Sep 17 '26

Other [2023 Day 17] In Review (Clumsy Crucible)

9 Upvotes

The lava is flowing again, and so the reindeer gives us a parachute and we return to Gear Island. Now we need to get the lava from the base of the lavafall to the parts factory, with minimal cooling, using hard to control crucible carts. And so we get a path search problem.

The input is a digit grid (141x141 in my input), with the digits 1-9 representing the cost (temperature loss) of crossing it. Just eyeballing the input it's easy to again see an ASCII art circular structure, and sure enough we have the large numbers more concentrated towards the middle, and the lower ones on the edges. There is no 0, so that's available if you want it for sentinels. And I do like my sentinel rings (only needed left and bottom for Perl and other languages with wrap around).

For part 1, our crucible can only move up to 3 tiles before needing to make a 90 degree turn (and reversing is not allowed). For part 2, it's an ultra crucible which must move at least 4 tiles and up to 10.

I remember this one well. First thought is that it's easy to build a state machine to do that movement. But then I thought that this is an intensive search, I'm going to want Dijkstra/A*, and I'm going to need to carry that state around. So after taking a break to think and put the tea on (it looked like it might take a while, but it didn't), I thought, "Is is really so bad to have a ply of 6?". And the answer is no... we'd get that sort of ply if we were doing this with moves in the 8 cardinal directions (backwards isn't allowed, leaving 7). And we wouldn't think twice then.

One thing to be careful about with large moves is jumping over a sentinel ring... that wasn't a problem for my code, because I generated them with a loop that takes one step at a time (even for part 2, where it just doesn't queue the first 3). You could also just make the ring thicker if you wanted to, or just go with checking the co-ordinates.

And so the idea was to queue moves for each range all at once. But you'd need the direction so you don't do a second move along it, or its reverse. And so then things coalesce... our atomic move is actually "turn and move a distance". The moves alternate between horizontal and vertical. And it eventually hit me that this is very much like splitters from yesterday... it doesn't matter exactly which direction you come into a tile, only the parity (horizontal or vertical), because there are only 2 sets of moves out. It doesn't matter if you came in from the left or right, every option from that point is the same. So the visit space is just 141x141x2.

I did throw in the basic heuristic of Manhattan distance to the end for my Perl solution. It doesn't really do anything though (times are the same). Especially for part 2, where as the examples showed, being too close is a problem, and your're going to need to loop around (and so it can be detrimental). And so I left that out when I did the Smalltalk solution. This is also one of the problems where my own Heap/Priority queue in Smalltalk outperforms the built in SortedCollection (14s to 16s).

The queue sizes max out at less than 6000 for part 1 and about 44000 for part 2. Which is a good sign, even with the large ply for part 2. An out-of-control queue size is typically a sign that your search space is too large and you're not pruning enough.

So this was a very nice problem... it's more about thinking about things than the algorithm. That's typically what makes a good search problem.


r/adventofcode • • Sep 15 '26

Other [2023 Day 15] In Review (Lens Library)

7 Upvotes

Following the newly focused beam we get to a large facility on the side of the largest mountain on the island. There we find the panicked reindeer that apparently hit the button that summoned us. Putting on goggles and a hard hat, we get lead to the room with the lens used for focusing, and need to arrange them at part of initialization to start up lava production. And we've turned around and are now going down on the ASCII art map.

The input for this one is one huge line (mine's almost 22900 bytes). The problem nicely warns people that are copy-pasting inputs to be careful. The string is a list of comma separated instructions, which are a label, an operator, and number (for =). Part one is writing a very simple function to hash a string (the Holiday ASCII String Helper algorithm). With that tested and working, we then implement a hashmap (Holiday ASCII String Helper Manual Arrangement Procedure) with it. All in the guise of putting lens into boxes.

This was a classic "do the job" type problem. If you've been using a language without built-in hashes, you may have written similar a few times. One slight quirk is that in part 1 you hash the full instruction, and in part 2 you only need to hash the label (it's a little thing for if you're trying to do both in one solution). Perl and Smalltalk both have hashmaps, but the also have nice lists as well, so managing those for the collisions isn't hard either. You do the hash, you look for label in the list at that box, and then splice, push, or set for Perl. For Smalltalk, it's:

box   := label reindeerHash + 1.
found := (boxes at: box) detect: [:l | l key = label] ifNone: [nil].

(oper = $-) ifTrue: [
    found ifNotNil: [ (boxes at: box) remove: found ].
] ifFalse: [
    focus := (step at: 3) asInteger.
    found ifNil:    [ (boxes at: box) add: (label -> focus) ]
          ifNotNil: [ found value: focus ].
]

One nice thing is that Smalltalk has base-1 indexing, so after the quirk of adding 1 to the hash to get the right box, everything is exactly at the index values you want for calculating the answer.

The hash function is simple, so I did do a quick dc solution for part 1 (list of lists would be a bit of mess, but not impossible):

rev input | perl -pe's#(.)#ord($1)." "#eg' | dc -e'[s.+0d]sS44?0d[3Rd44=S+17*256%z2<M]dsMxrp'

Still using the ?, but it's only used here to put the input over top of a 44 (the ASCII value of comma, to make all instructions end with one). So it still works with the new version of dc, but it prints the entire input as well.

This is clearly a bit of a break day. It was a Friday in 2023, so it was probably a good day for some people to get things in order before the weekend problems arrived.


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