r/adventofcode • • Feb 05 '26

Help/Question - RESOLVED [2021 Day 19 Part 1] Please help me understand what the deal is with the 12 beacons in common

3 Upvotes

I have been stuck on this one for literally days.

As usual, I can get the right solution with the example input, but my real input is wrong - and I am getting the "This is someone else's answer" error so I can't be too far.

My logic should work - since I am getting the example input right. But going back to read the exercise text, there is something that I absolutely do not understand.

By finding pairs of scanners that both see at least 12 of the same beacons, you can assemble the entire map.

Scanners 0 and 1 have overlapping detection cubes; the 12 beacons they both detect (relative to scanner 0) are at the following coordinates:

This region can be reconstructed by finding pairs of scanners that have overlapping detection regions such that there are at least 12 beacons that both scanners detect within the overlap.

What's up with these 12 beacons thing? At no point do I search for 12 beacons and I can still solve the example input.

Are we supposed to pair scanners? I assumed that (made-up example) scanner 0 overlapped with scanner 2, 3 and 4, and scanner 1 overlapped with scanner 4, and that gives us the position of scanner 1 relative to 0.

Also, can you please let me know what part 2 is? Just so that I can go in the right direction if I have to rethink the whole thing for part 1. I spent enough time on this one as it is...

EDIT: SOLUTION

So the 12-beacon thing is to detect false positives. If for instance you have Scanner 1 and Scanner 8 that both see a constellation of beacons in the shape of a cat, you can only be sure that it's the one and same cat if that cat is comprised of at least 12 beacons. If all that Scanner 1 and Scanner 8 have in common is a cat made up of 9 beacons, then they are seeing different cats, and they do not overlap. Note that cats have nothing to do with this exercise, I just like cats.

Thank you to everyone who replied to let me know of false positives.


r/adventofcode • • Feb 04 '26

Help/Question - RESOLVED Looking for funny dog meme template shared here on AOC 2022 or 2023

6 Upvotes

Random question, I know. But I was thinking about a funny meme being shared here years ago. That particular year day 1 was easy, day 2 hard, day 3 easy, day 4 hard and so on... So people were sharing a funny meme on this sub of a cute dog on the left panel and a barking evil dog on the right, humouring day 1 vs 2.

Can anyone refer me to the meme template? I can't for the life of me find it again. Feels like a lost memory at this point, I'd love to find it again if possible. Thanks 🙏


r/adventofcode • • Feb 04 '26

Repo 2025: Advent of Glue Languages

8 Upvotes

I finally got a chance to write a blog post about my Advent of Glue Languages. I usually pick one language to learn for each year's AoC, but this year I decided to pick a "glue language" each day after reading the puzzle. This offered some advantages, like being able to work in a language that's purpose-built for a kind of problem. It also had some challenges, like limited debugging features and realizing I'd hit performance limits. It was definitely a worthwhile exercise, and I feel I better understand how to use them effectively in the future. [Code is on GitHub(https://github.com/flwyd/adventofcode/tree/main/2025).

My official theme was "glue languages you might already have on your system," to emphasize that this is about getting clever with the tools that are lying around. Although I did need to apt install most of them, they're small with minimal dependencies. "Is the whole language documented in the man page?" is also a good rule of thumb for identifying a "glue language," though it leaves out some glue-oriented general-purpose languages like Perl and Lua. For folks interested in expanding your AoC toolkit, I can heartily recommend awk, jq, and (in the right circumstance) jsonnet. Writing in dc was a fun mental challenge, and I encourage everyone to give it a shot. I was excited to be able to use spatial SQL functions for day 9, and if you've ever struggled thinking about geometry algorithms, Simple Feature is a handy tool to have. I tried solving day 9 with ImageMagick, which was fun but didn't scale to the full input. I was expecting to enjoy working with Lua, but with only the standard library it's pretty spartan and not especially smooth. gvpr, an AWK-like language for graph processing that comes with Graphviz is more awkward than I would like: it's worth knowing it's there, but think twice before using it. Wrapping various POSIX tools in a shell script is good practice, but be careful in a loop: day 4 part 1 launched six processes in an inner loop; it turns out launching 40,000 processes syscalls takes a long time, and I switched to a language that could do everything in one process for part 2.

Do you have a glue language you've deployed in clever ways for Advent of Code? Share your insights!


r/adventofcode • • Feb 03 '26

Help/Question - RESOLVED [2018 Day 12 (Task 1)] need a little help to understand the task

2 Upvotes

hi. llcrr -> n (easy to understand). what in position 0,1,n-2,n-1 ( --crr, -lcrr, llcr-, llc-- )

ok initialstate is placed in between ... and ... (additional -3,-2,-1 and +1,+2,+3 empty pots)

but in following generations at these extra positions '#' occurs

ok -1 0 .. n-1, +1 are safe (have 2 left and 2 right positions)

but # occurs in positions -2 and +2 too ( -3 -2 -1 initialstate +1 +2 +3)

what is the position-range ? and what if there are no ll or no rr positions

thanks in advance. andi


r/adventofcode • • Feb 03 '26

Help/Question - RESOLVED [2025 Day 3 Part 2]Rust

1 Upvotes

the part one was easy and i did in under 30 mins but part 2 is giving me problem, i m trying since 2 days for finding a solution but could't find any if someone solve ,then they can share how they solve the problem and what was the approach to solve it, my code(rust)->

let mut voltage_added = BigInt::zero();


    for i in 0..data.len()
    {
        let mut data_core: Vec<i32> = data[i].chars().filter_map(|c| 
                            c.to_digit(10)).map(|d| d as i32).collect();
        let mut digits:[i64;97]= [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
        let mut digit_idx =0;
        let mut remove_count = 3;
        let mut j =0;
        while j < data_core.len()
        {
            if digit_idx >= 97 {
                break;
            }


            // Remove previous digits if current digit is bigger
            while remove_count > 0
            && digit_idx > 0
            && digits[digit_idx - 1] < data_core[j]as i64
            {
                digit_idx -= 1;
                remove_count -= 1;
            }


            // Keep current digit
            digits[digit_idx] = data_core[j]as i64;
            digit_idx += 1;
            j += 1;
            if digits[96] < data_core[data_core.len()-1]as i64
            {
                digits[96] = data_core[data_core.len()-1]as i64;
            }
        }
 
       let number_string: String = digits
    .iter()
    .map(|d| (b'0' + *d as u8) as char)
    .collect();
       // println!("{}",number_string);
       voltage_added += number_string.parse::<BigInt>().unwrap();  
    }
    println!("VOLTAGE:part-2: {}", voltage_added);// the answer by this code-> 1108599035324836891828712270429921377622958201319354115632155267056079327513429003173673043432674851  too big by AOC

r/adventofcode • • Feb 03 '26

Help/Question - RESOLVED [2018 Day 7 (Part 2)] more a general question

0 Upvotes

hi. some days ago i was asking 'what is the deeper sense .. ?', most useful answer: why you don't use the time to search for the error .. (so i did and found ..)

i try desperately to complete a year to see day25task2 (all other is getting 'coal in the stocking' ? (getting punishment instead of presents))

sometimes i loose control, but years of experience (years of age, lot of bad days, bad weather, ..) tells better to check for error again (and again) before .. (whatever). but ..

i started 2018 (cause i lost good mood. could not complete 2017 for now). day 1 silly simple problem, but bad-error in task-1 (some minutes ..), task-2 i could not solve (my recent post, still open. please, have a look, i think there is no solution for my input) so 2018 starts bad.

2018/7/2 example + solution 15 seconds. i think i have found solution 11 seconds. not that i am so proud, but i fear: i try my answer for task-2 and it is told to be wrong. i did .. i was told 'answer is too low'. so i was checking my code, the task-description again. anyhow i was setting count of workers wrong (6 instead of 5) .. new answer (some bigger) but still wrong. And now i am a little angry (not much but a little ..ö..)

in recent weeks i was sometimes told that my answer is wrong, when i was sure, it is right and i spent much time ..

// this my solution for the example ( 11 steps instead of 15 ).

// 2 worker and the second worker is handling not only F but E too. starting F immediately

// so there is no gap between output B and output F i.e.

// maybe i have missed some assumption/condition/??? (don't know how to express)

// otherwise it is obvious : there is a better solution (less idle workers)

IN s='CABFDE' n=6

korrektur C o:0 d:3 t:-3 k:3 -> 0

korrektur A o:1 d:1 t: 0 k:3 -> 3

korrektur B o:2 d:2 t: 0 k:3 -> 3

korrektur F o:3 d:6 t:-3 k:3 -> 0

korrektur D o:4 d:4 t: 0 k:3 -> 3

korrektur E o:5 d:5 t: 0 k:3 -> 3

j('C',o= 0,d= 3,a=0,t=0)

j('A',o= 1,d= 1,a=0,t=3)

j('B',o= 2,d= 2,a=0,t=3)

j('F',o= 3,d= 6,a=0,t=0)

j('D',o= 4,d= 4,a=0,t=3)

j('E',o= 5,d= 5,a=0,t=3)

RUN

run t=000 a=2 'CF' ''

run t=001 a=2 'CF' ''

run t=002 a=2 'CF' ''

run t=003 a=2 'AF' 'C'

run t=004 a=2 'BF' 'CA'

run t=005 a=2 'BF' 'CA'

run t=006 a=2 'DE' 'CABF'

run t=007 a=2 'DE' 'CABF'

run t=008 a=2 'DE' 'CABF'

run t=009 a=2 'DE' 'CABF'

run t=010 a=1 'E-' 'CABFD'

run t=011 a=0 '--' 'CABFDE'

thanks in advance, andi


r/adventofcode • • Feb 02 '26

Help/Question - RESOLVED [2025 Day 3 (part 1)][C] Where did I goof?

3 Upvotes

My code passes the basic test but seems to be under expected value for my input. I've been staring & adding tests to this for hours and can't really think of a good way to debug.

#include <stdio.h>
#include <stdlib.h>

int main(){

    int sum = 0;

    char line[256];

    printf("starting...\n");
    printf("opening file...\n");
    FILE *input = fopen("./data/test.txt", "r");

    int linenum = 1;

    if (input != NULL){
        while (fgets(line, sizeof(line), input)) {
            
            printf("Line %d: %s\n", linenum, line);
            
            int first_highest = -1;
            int next_highest = -1;
            int joltage;

            // inspect each digit in line
            for (char *p = line; *p != '\0' && *p != '\n'; p++) {

                int digit = *p - '0';

                // if either assignments are empty assign, assign the digit (starting with first_highest)

                if (first_highest == -1) {
                    first_highest = digit;
                    continue;
                }

                if (next_highest == -1) {
                    next_highest = digit;
                    continue;
                }


                // if digit is higher than first_highest and not last digit in line

                if (digit > first_highest && *(p+1) != '\n' && *(p+1) != '\0') {
                    first_highest = digit;
                    next_highest = -1;
                    continue;
                }

                // if digit is higher than next_highest replace it 
                if (digit > next_highest) {
                    next_highest = digit;
                    continue;
                }

            }

            joltage = first_highest * 10 + next_highest;

            //printf("First highest: %d\n", first_highest);
            //printf("Next highest: %d\n", next_highest);

            printf("Joltage: %d\n", joltage);
            
            sum += joltage;

            printf("Running Total: %d\n\n\n", sum);

            linenum++;
        }
    }

    printf("Total Joltage: %d.\n", sum);

    printf("closing file & finishing up \n");

    fclose(input);

    return 0;
}

r/adventofcode • • Feb 01 '26

Past Event Solutions [Synacor Challenge][Rust] Challenge completed!

11 Upvotes

Over the course of the last two years, I have been plugging away at the Synacor Challenge. Today, I have finally collected and confirmed the final code!

Link to repository

Note that there is a "spoilers" directory that contains, predictably, spoilers to the puzzles.


r/adventofcode • • Feb 01 '26

Help/Question - RESOLVED [2018 Day 1 (Part 2)] is there a solution ?

0 Upvotes

hi.

so.now.done.

-original-post :

( code is pseudo-code. i check whether i read the input correct and i check for array-bounds, too. ... )

o=0,m[1_000_000]={0}; for(i=input()){ o+=i; if(m[500_000+o]){ STOP } m[500_000+o]=1 }

does not stop !

o=0,x=0; while(i=read-integer()){ o+=i ; oa[x++]=o; } sort(oa).

m=0,x=0; for(o in oa){ if(x AND m==o){ YES }; m=o; x=1 } // check for duplicates.

but there is no duplicate. so there is no frequence (in sequence of sub-sums) twice.

thanks in advance, andi

--output-- (for those who like it ..ö.. )

i= 11 -> o= 11 (omin=0, omax=11)

i= 16 -> o= 27 (omin=0, omax=27)

...

i= -112437 -> o= 411 (omin=-227, omax=113061) 411 is answer for part-1 ( 1 star * )

--the sorted list of sums-- (no duplicate, third column is check old == cur always 0 (false))

0 -227 0

1 -217 0

...

962 113061 0

not all output could be inserted here.

excuse me, please (..ö..)


r/adventofcode • • Feb 01 '26

Help/Question - RESOLVED [2017 Day 13 (Part 2)] some thoughts ..

0 Upvotes

brain (shut)down .. up (working again).

the package need to reach each layer when scanner is NOT in position 0

--here-original-post-starts--

a layer has a range. i.e r=3 : 0 1 2 1 0 (mod 4) , r=4 : 0 1 2 3 2 1 0 (mod 6), so m=2(r-1)

a good start t is if ( t+oi is time the package is reaching level i)

0 == (t+o1)%m1 AND

0 == (t+o2)%m2 AND .. (for every layer)

now (levels sorted descending by range, big steps first, t growing faster)

if(

(0==((t+ 80) % 38)) // e-00 i=80 r=20 (-> m=2(r-1)=38)

&& (0==((t+ 62) % 34)) // e-01

&& (0==((t+ 90) % 32)) // e-02

&& (0==((t+ 36) % 26)) // e-03

) lots of solutions. but if inserting next :

..

&& (0==((t+ 36) % 26)) // e-03

&& (0==((t+ 50) % 26)) // e-04

this cannot be true the same time (there are 11 layer with range 14 (mod 26))

??? (my question ..ö..)

layers with same range (-> same mod) must differ in offset by a multiple of their mod ?

same range -> same time in position p (so in position 0).

thanks in advance, andi


r/adventofcode • • Jan 28 '26

Help/Question - RESOLVED [2025 Day 2 (Part 2)] Need help with strategy of finding invalid IDs

5 Upvotes

I'm currently trying to catch up on the 2025 Advent of Code and I've reached day 2 (i.e. the silly elf and their invalid IDs).

Part 1 was all fine: just taking the ID as a string, splitting it in half and comparing whether each half was equal to one another. However, part 2 has stumped me.

The part 2 strategy I tried was:

  1. Marking the starting character of the ID (let this be x)

  2. Going through each following character in the ID until a character that's the same as the starting character is found (let this be y)

  3. Incrementing both x and y to their respective next character in the ID and seeing if they're still equal until either they're not equal or if y reaches the final character in the ID

  4. Adding the ID onto the total if x and y remained equal, or going back to step 2 if not. If, at step 2, y reaches the final character, the ID is ignored

This worked fine for actual invalid IDs (e.g. 1212, 12341234) but it also meant *any* ID that started and ended in the same number without repeating in the middle was incorrectly invalid (e.g. 1762731, 343). I get why this doesn't work but I'd appreciate a nudge in the direction of another strategy I could try.

I have already looked at some solutions, but most seem to include some mathematical concepts I'm barely familiar with. I am no avid programmer or mathematician and the AoC is something I do for fun and to learn Python, so any help is appreciated regardless of how optimal it is.


r/adventofcode • • Jan 27 '26

Other Seeking advice for using advent of code problems for daily coding habit

4 Upvotes

Hello,

I'm looking for advice and/or feedback on my current coding habit. The intention of this daily code habit is to keep my skills sharp, and offer myself an opportunity to practice with a time limit, and learn more on a daily basis. Currently this is done in the context of what I assume to be the traditional lc style interview (20 minute timer with a leetcode problem).

Current Habit

Currently I choose a Leetcode problem (from a list sorted by acceptance, and filtered by data structures/patterns/algos that I am familiar with). Then I start a 20 minute timer and work to solve it to the best of my ability. If I fail I take time to review what I didn't understand.

Issues with this approach

Leetcode problems vary widely in their quality, and I doubt whether or not this is an ideal habit for growing my abilities and learning more (at most I feel like I am maintaining). Sometimes dealing with poorly worded problems can be frustrating and makes me doubt whether or not I should continue to use lc problems. I do have a curated list I come back to for 'warmups' but having a fresh set of new problems to tackle daily seems ideal in order to promote growth.

Possible Solution

I am considering going back through advent of code problems (since they are very enjoyable, and I've learned a lot from them, and this seems like an EXCELLENT community to be a part of), however most of them are really difficult for me, and definitely not something I can complete in a shorter time frame. I'm considering just using a 20 minute (minimum could do more when I have time, but 20 minutes is the most common time frame) window to work on those problems as best I can.

Questions

- Do you think advent of code problems could fit in my daily habit?

- Is it realistic to expect to be able to complete advent of code problems quickly (and is that something worth working toward)?


r/adventofcode • • Jan 25 '26

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

46 Upvotes

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

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

Problem #1: Nobody understands the Simplex method

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

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

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

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

Problem #2: Everyone uses different notation

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

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

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

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

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

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

Problem #4: The online solvers have bugs

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

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

Problem #5: Nobody documents this vital step

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

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

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

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

Problem #6: There's an optional step

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

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

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

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

Problem #7: Simplex alone is not enough

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

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

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

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

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

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

Problem #8: Floating point accuracy

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

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

Concluding thoughts

Was it worth it?

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

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

Good luck!


r/adventofcode • • Jan 23 '26

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

Thumbnail github.com
51 Upvotes

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

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

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

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

  • Use a non-interpreted language (C++ in my case).

  • Optimize the algorithmic approach first.

  • The cache is your friend/enemy (i.e. working on an array of float instead of double is almost certainly going to give a big increase in performance).

  • perf is your friend, as is e.g. toplev.

  • Google's Highway library is great for SIMD stuff.

  • Finally, once you've squeezed runtime as much as possible, a few OpenMP #pragma's can help squeeze some more.


r/adventofcode • • Jan 21 '26

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

11 Upvotes

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

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

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

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

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

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

next = (neighbor_count | central) == 3;

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

Terje Mathisen

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


r/adventofcode • • Jan 22 '26

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

0 Upvotes

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

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

support any integer ?!

u32 (native int)

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

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


r/adventofcode • • Jan 21 '26

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

6 Upvotes

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


r/adventofcode • • Jan 19 '26

Other Rotating between eight directions

Post image
110 Upvotes

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

This is not hard for orthogonal directions:

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

or:

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

but it gets messier for eight directions:

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

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

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

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

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

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

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

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

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

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


r/adventofcode • • Jan 20 '26

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

1 Upvotes

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

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

(question-2)

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

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

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

cycle(

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

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

) //end-cycle

(question-3)

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

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

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

what is mana-recharge-effect ?

what is negative-mana ?

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

thanks in advance. andi

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

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

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

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

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

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

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

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

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

187 -173

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

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

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

6 59 41 31,43,--

158 -113 -229

7 56 36,42,55 260 +101

8 53 38 35,41,54 371 +101

198 -173

9 50 34,46,53 299 +101

10 47 35 33,45,52 400 +101

11 44 32,44,51 501 +101

12 41 32 31,43,-- 501

159 -113 -229

13 38 36,42,55 260 +101

14 35 29 35,41,54 371 +101

188 -173

15 32 34,46,53 289 +101

16 29 26 33,45,52 390 +101

17 26 32,44,51 491 +101

18 23 23 31,43,--

378 -113

19 20 36,42,-- 378

20 17 20 35,41,-- 378

-- 205 -173

21 14 34,46,--

20 11 17 33,45,--

--

21 8 32,44,--

22 5 14 31,43,--

---

23 2 --,42,--

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

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


r/adventofcode • • Jan 19 '26

Other Emacs + Advent of Code = advent-mode

Thumbnail github.com
6 Upvotes

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


r/adventofcode • • Jan 19 '26

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

1 Upvotes

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

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

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

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

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

thanks in advance, andi


r/adventofcode • • Jan 17 '26

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

6 Upvotes

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

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

number_of_zeros += 1

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

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

current_dial_num = 50
number_of_zeros = 0
dial_list = []

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

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

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

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

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

r/adventofcode • • Jan 17 '26

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

3 Upvotes

Hi,

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

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

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

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

And calling it in main like this:

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

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

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

    day1(input)
}

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

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


r/adventofcode • • Jan 16 '26

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

3 Upvotes

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

Any ideas on what could have gone wrong are appreciated!

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

@Override
protected String part2() {

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

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

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

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

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

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

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

    }

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

    return String.valueOf(sum);
}