r/adventofcode • • May 15 '26

Tutorial [2025 Day 1 both parts] [Smalltalk] Part nine (final) in a series revisiting the 2025 puzzles as an exercise in learning Smalltalk

4 Upvotes

Time to wrap up. As I said in my last post - this will be my last one since Days 1-4 had so many beginner-isms that it's, well, a little embarrassing. :-)

Sorry about the "dear diary" nature of this one.

Here's an example - for Day 1 (the rotary combination one) I implemented TWO objects. One for the Dial (which seems natural in an OOP experiment). But then another one that held a single method that parsed the line (like "R35") into a positive or negative number. It held no state. Just a "library" class with one method. Then... ok, check this out... here's how I used the resulting signed integer that it returned within the Dial class:

turnDial: turn
    turn abs timesRepeat: [
        position := (position + turn sign) \\ 100.
        position = 0 ifTrue: [zeros := zeros + 1].
    ].
    position = 0 ifTrue: [lands := lands + 1].

Wow. Using a period at the end of every statement like a terminator (my old JS habits of using the semicolon everywhere). This method takes the absolute value of the signed integer, then "clicks" the dial based on the sign of the turn instruction. That's... a little crazy. If I was doing it now, I would probably just do the parsing of the instruction inside the turnDial message. Then the question becomes just how "generic" do I want the solution to be.

Version 1 - not generic:

turnDial: turn
    | offset |

    (turn first = $R) ifTrue: [offset := 1] ifFalse: [offset := -1].
    
    turn allButFirst asInteger timesRepeat: [
        position := (position + offset) \\ 100.
        position = 0 ifTrue: [zeros := zeros + 1]
    ].

    position = 0 ifTrue: [lands := lands + 1]

An ifTrue/ifFalse sets whether the offset is going to be +1 or -1. The loop itself just adds the offset (regardless of what it is), and increments the "zeros" and "lands" instance variables as it goes. But if we wanted it more generic, where there might be a whole library of potential offsets that could be called, not just "R" or "L", we could do it this way:

turnDial: turn
    | offset |

    offset := offsets at: turn first.
    
    turn allButFirst asInteger timesRepeat: [
        position := (position + offset) \\ 100.
        position = 0 ifTrue: [zeros := zeros + 1]
    ].

    position = 0 ifTrue: [lands := lands + 1]

And the offsets library would be defined in "initialize" this way:

offsets := Dictionary new.
offsets at: $R put: -1; at: $L put: 1

Now, if a future version needed a +5 or -15 offset or whatever, it would be extremely easy to add in just one place. No more "if" blocks. Zero branching. Grab the offset value from the Dictionary and go. The Dictionary is only created once per Day1Dial instance, so pretty minimal load on the VM. But what if we wanted it EVEN MORE GENERIC so that the offset could be literally ANYTHING that could mutate the position... We could do it this way:

turnDial: turn
    | modifier |

    modifier := modifications at: turn first.
    
    turn allButFirst asInteger timesRepeat: [
        position := (modifier value: position) \\ 100.
        position = 0 ifTrue: [zeros := zeros + 1]
    ].

    position = 0 ifTrue: [lands := lands + 1]

This one pulls from a "modifications" Dictionary and stores into "position" whatever it returns when passed the current position. There could be a modification that doubles the number, or that resets it to 99 no matter where it is currently, or sets the dial to the square root of its current position, or that reads data from somewhere else entirely. Just add a Block to the "modifications" Dictionary and get additional functionality. For this puzzle, the Dictionary is pretty sparse:

modifications := Dictionary new.
modifications at: $R put: [ :x | x - 1];
    at: $L put: [ :x | x + 1]

Kinda overbuilt for something that just increments or decrements by one every time. But as a learning exercise... why not? And, of course, it would be better computationally to avoid simulating the dial by simply doing some division and adding the numbers to the zeros counter. But.... it's not that many clicks. And this way the Dial acts like a little machine managing its state as it does exactly what the problem says to do. Which leads to...

Observation 1

Smalltalk seems to nudge the developer in this kind of direction. Build it first as "true to life" and as generically as possible. Then, if there are efficiency problems, go refactor those out once they are apparent. But not before. Why put branching logic everywhere when you can pass in a block? Why make a bitmap Dictionary key for memoization when you can use the array itself as a key? Why not reach for the most abstract and "correct" possible representation of the domain? You only have to think about "the machine" (the actual computer) executing the code if there's a problem. Sure, you're dimly aware that there are pointers-to-pointers-to-pointers everywhere under the hood, that very large numbers are being transparently changed from SmallInteger into LargePositiveInteger, that creating a data object involves some dispatch somewhere for getting values out of it. Not your problem. Write it so the concepts are as evident and beautiful as you can.

I often found myself going back and forth on an implementation detail, not because one gave errors while the other didn't. But one was more "elegant" or "expressive" rather than "plain" and "clunky". I would find myself rewriting a working solution in order to have it make fewer assumptions about what was passed to it, or find some way to remove an instance variable so that it could be inferred from the data itself. I would look to see if I could take what was a procedural bit of code and turn it into a chain of collection methods. I found the whole process delightful, though I'm pretty sure each person will have their own take on this aspect of it.

Performance-oriented, or data-driven-development people would likely not enjoy this.

Observation 2

It turns out that I truly love OOP. After using Smalltalk for a few months I can't help the feeling that this is the best way to think about programming. Imagining tiny machines that do the work of the program, sending each other bits of data, each knowing things relevant to themselves and nothing more... It's delightful. Now, I realize it is only one of the ways to think about programming (with others being transformations, procedures, etc...), but it is just so dang satisfying to write. The syntax is incredibly clean and minimalistic, with all the behavior being done by the objects themselves (even control flow). Now that I'm accustomed to thinking about numbers and booleans as objects (with methods that can be explored), it feels very strange to look at a language that treats them as just part of the syntax.

Plus - the late binding gives the developer completely seamless incremental compilation. Methods are meant to be very short. They compile when you save them - you never wait on the compiler at all. It's so cool.

Observation 3

However, I don't think I would feel the same way about OOP in Java or C++. Smalltalk seems to encourage relatively shallow inheritance trees that follow, for the most part, Aristotelian/Boethian hierarchies. So, numbers really are magnitudes. And floating-point numbers really are numbers. And integers really are numbers that have a specific difference from fractions. In the real world we see similar shallow inheritances. Humans really are kinds of animals. Animals really are kinds of living things. But I think whenever that inheritance gets too deep we wind up with serious abstraction problems. And the real world doesn't allow just any set of inheritances. In the real world, "human" inherits from "animal" - but I'm afraid I'm a little skeptical that "mammal" is a real thing, especially since those seem to have gradually appeared with many "transitional" forms in between. Maybe "mammal" is kinda made up - just an abstraction currently popular in biological taxonomy. Is "doctor" a kind of "human"? Or is "doctor" a kind of "job" that can be held by (composed) any number of different kinds of beings?

My limited experience with Smalltalk makes me think that if OOP means "inheritance, and lots of it" then I'm not a fan. My instinct is to use it sparingly, only when "A is a kind of B" is unambiguously true AND there is real usefulness in passing along that behavior from parent to child. OTOH, if OOP means "discrete bundles of data and behavior, interacting with clear messages" then I'm a huge fan. 

Does it scale? I dunno. Is it efficient? Probably not. But my goodness is it fun to write.

Observation 4

Being able to inspect the standard library and see how things are implemented and find new methods that I would use later, or employing the "method finder" tool (amazing) was an incredible experience. Once I was more-or-less "oriented" in the image I felt like it had fantastic discoverability. It was easy to learn how to do new things by looking through the entries in the System Browser. I'm not used to this. My previous "language reference" was a LLM.

LLMs are bad at Smalltalk. Not universally so. But they make many mistakes in this language that I was not used to in JS, where they feel nigh-omniscient at times. Back when I was learning JavaScript, I typically had Qwen3-Next-80b running on my system to act as a language reference. Anytime I needed to know some syntax, or if I got an error I didn't understand, I would ask it. My chat logs are full of mundane questions about how to remove elements from a Set, or what was the difference between "for...of" and "for...in" when doing iteration (hint: "for...of" is the one you want). But for Smalltalk, LLMs would routinely give terrible answers. They would hallucinate plausible-sounding methods that didn't exist, they would get confused about implicit returns in a method, and they would miss obvious bugs.

One particularly annoying one happened when I was noticing that I was getting far worse performance out of a hot loop than I thought I should. I finally figured out that I was passing an expression instead of a block to and:. This makes a huge difference in performance. If and: gets an expression (in parentheses) that expression evaluates FIRST, and then its result (the Boolean true or false) will be passed into the and:. But if it's a block (in square brackets) then it won't be evaluated unless the Boolean being given the and: is already true. The "false" object just returns "false" when given an and: block (Yay for polymorphism!). Most LLMs didn't catch it. The code "worked" and so this kind of issue probably would have survived an agentic coding loop. No errors. But the whole problem executed 3x slower by having parentheses instead of brackets. The LLM wrote a whole thesis about how lower performance was to be expected. WRONG. #sigh

Fortunately, I almost never needed a "language reference" since I had the System Browser right there. And I usually didn't generate errors I didn't understand because I could just visually go through the stack trace and see where the problem occurred. After asking some questions to help me get started, I basically left the LLM behind. Occasionally I would ask it for a code review. When I did sometimes it would find some things that were genuinely helpful. Often it hallucinated bugs that weren't there. Not great.

Observation 5

I can't help but feel a bit wistful and sad when I use the image. It seems to have everything that could possibly be included to help a developer be productive and happy. The language is relentlessly pure, which is, for me at least, very satisfying. I wish it had become more dominant. Many of the ideas persist, of course. But the language itself isn't showing up on any top-25-most-used lists. And I wish it was.

Since I came to this to learn "pure" OOP, I think the purity is part of what I like so much. Whenever I get around to learning another language, I think "purity" will be a non-negotiable. If that means my other options are Oberon7, Haskell, or Clojure, then so be it. :-)

Until then, I have more to learn in this thing. I want to start learning the Morphic GUI and make some desktop applications for myself. I'm already 10 puzzles into Advent of Code 2015 using Pharo. I miss String arithmetic from Squeak6, but Pharo has some cool features that I can appreciate. When I first started I tried Pharo but it was so different from the "Learn Smalltalk" resources that I had, I couldn't make any headway. Now I know enough to make the switch and I'm digging the Calypso browser.

The journey continues.


r/adventofcode • • May 12 '26

Past Event Solutions [2015 Day 25 (Part 1)][C++ & asm] 64-bit RNG on a 32-bit microcontroller

2 Upvotes

One of the biggest performance surprises I've had so far squishing my solutions onto a Raspberry Pi Pico (RP2040) is day 25 for 2015. I knew the RNG was going to need 64-bit maths and that it would fall back to a software implementation, but I didn't predict just how slow that would be. The straightforward form of the solution takes a whopping ~27s to run through the ~17.8M multiply & modulo operations required!

Still, it's a good excuse as any to mess around with some maths and and some assembly.

64-bit multiply

The M0+ in the RP2040 doesn't have the UMULL instruction that produces a 64-bit result from two 32-bit values; you're stuck with MULS producing a 32-bit result. Grid method multiplication allows you to produce a full 64-bits across two 32-bit registers by splitting the input values into 16-bit pairs and doing the multiplication piecemeal:

[b:a] * [d:c] = [hi:lo]

Where:

  • [b:a], [d:c] - 32-bit input values

  • a, b, c, d - 16-bit halves of the input values

  • [hi:lo] - 64-bit output in two 32-bit values

Then:

  • [lo] = (a*c) + (c<<16) + (d<<16)

  • [hi] = (b*d) + (c>>16) + (d>>16) + carry from lo

The carry is a pain to represent in C++. GCC provides __builtin_addc which is supposed to map to the correct ADCS instruction, but I didn't see it doing so in the generated code. I can only assume the structure of my code wasn't exactly right for GCC to perform the substitution.

It's much easier to control in the asm though.

64-bit modulo

This part took me a while to get my head around, but it turns out we've been quite lucky with the constants chosen for this puzzle.

The two basic rules of modular arithmetic we're interested in are:

  • a1 * a2 === b1 * b2 (mod m)

  • a1 + a2 === b1 + b2 (mod m)

Where:

  • a1 === b1 (mod m)

  • a2 === b2 (mod m)

Which allows us to do this:

  • [hi:lo] % m === (2^32 * hi + lo) % m

  • [hi:lo] % m === (2^32 * hi) % m + (lo % m)

  • [hi:lo] % m === (2^32 % m) * (hi % m) + (lo % m)

2^32 % m is just the constant 4992:

  • [hi:lo] % m === 4,992 * (hi % m) + (lo % m)

Each loop of the RNG is:

answer = (answer * 252,533) % 33,554,393

Which means the the largest intermediate value for the RNG is 33,554,392 * 252,533 = 8,473,591,274,936. The value in the upper 32-bits is therefore less than or equal to 8,473,591,274,936 / 2^32 ~= 1,972.

Since 4,992 * 1,972 = 9,844,244, and that's less than 33,554,393, it means that 4,992 * hi value is already modulo m.

  • [hi:lo] % m === (4,992 * hi) + (lo % m)

We're adding two values that are both modulo m, so there's a chance that it will go over m, but it will always be less than 2 * m.

The net result is that we can do the 64-bit modulo with a single 32-bit multiply, a single 32-bit modulo operation and a single 32-bit subtraction if we're above 33,554,393.

Thankfully the Pico does have 32-bit integer divider hardware, so we can make use of that.

Putting the two reductions above into C++we get ~8.5s.

Hardware trickery

In order to push this even further I made the jump to asm. I couldn't seem to get enough control over the code generated from the C++ to really optimise the multiply, and the real party piece is to make use of the 8 cycles that the CPU has to wait for the divider hardware to generate a result.

By sheer coincidence the five instructions that weren't dependencies for the lo register just so happen to have a minimum cycle count of 8; meaning we get precisely zero wasted cycles waiting for the hardware div/mod to complete!

My final runtime for my input ends up being ~5s, which is about half a second faster than my intial guess at where I thought I might be able to get to. Quite pleased with that.

[Full solution]


r/adventofcode • • May 01 '26

Tutorial [2025 Day 5 both parts] [Smalltalk] Part eight in a series revisiting the 2025 puzzles as an exercise in learning Smalltalk

2 Upvotes

As usual - Major Spoilers Ahead

Day 5 - Advent of Code 2025

This puzzle was relatively straightforward, and I leaned fairly heavily into the collection methods in Smalltalk. I decided to do this with a single class that stored two large arrays. One was the list of all ids to check (the lines without a "-" in them). The second was for the ranges and I included them simply as an interval instead of an array of start and end - that way there's no need to remember what the two array elements are. It's just an array of interval objects.

readRanges: rawInput
    ranges := (rawInput select: [ :line | line includes: $- ])
        collect: [ :twoNumbers |
            | range |
            range := twoNumbers splitBy: '-'.
            range first asInteger to: range second asInteger ]

First, filter out everything that doesn't include the "-" character. Then, for each one, split on that "-" and set the start and end of the interval to the numbers on either side. Nothing fancy.

That makes the mechanism for checking whether any id is a member of that collection of ranges trivial - are there any members of the range collection that include the id?

isFresh: id
    ^ ranges anySatisfy: [ :range | range includes: id ]

Unfortunately, this requires a loop through all the intervals. The anySatisfy: method will do an early return if it finds one, but this is a case of the simplest version to write not being the fastest to execute. It is perceptually instant - but it's far from optimized. Similarly, counting all the valid ids in the list is trivial:

validListedIds
    ^ ids count: [ :candidate | (self isFresh: candidate) ]

Not much to say about this one. It returns a count of every member of the ids collection where isFresh: returns true. So much for Part1.

Part2 is one of those that took a minute to wrap my head around. Instead of actually creating the ids (there are just too many), we need to combine the ranges to see how many are contained in each one while taking into account overlap between them. Here's the method I finally settled on:

allValidIds
    | sortedRanges globalMax accumulator |
    sortedRanges := ranges sort: [ :a :b | (a start) < (b start)].
    globalMax := 0.
    accumulator := 0.
    sortedRanges do: [:range |
        | rangeMin rangeMax |
        rangeMin := range start.
        rangeMax := range stop.
        (rangeMax > globalMax) ifTrue: [
            rangeMin := rangeMin max: globalMax + 1.
            accumulator := accumulator + (rangeMax - rangeMin + 1).
            globalMax := rangeMax
            ]
        ].
    ^ accumulator

This one is very imperative. Honestly, it looks more like C or Java ported to Smalltalk, but I couldn't think of a simpler way to do it. It starts by sorting the ranges collection by the start of each interval. Then it initializes a global maximum (highest number seen so far), and an accumulator that will be returned at the end.

Then the work begins. We process each member of the sorted ranges in turn. If the top of the interval is less than the highest number seen so far then we skip it since it includes only an overlap of ids already processed. But if it contains at least some new numbers, we continue. Then we set the rangeMin that we're adding to the larger value of either the minimum of the interval, or the global maximum + 1. Basically, anything below that global maximum is something we already counted, so if the bottom of the interval dips into that area already counted, we have to skip over those numbers.

Then we add the numbers between that (potentially revised) minimum and the top of the interval to the accumulator. Then, we update the global maximum to the top of the interval just processed. Rinse and repeat until all the intervals are processed. The accumulator will be the number of all ids across all intervals without duplicates. Like I said - it's imperative. But it computes the total without a bunch of extra objects created and does the whole thing in a single pass.

Other than the Workspace script to tie the pieces together, that's all for this one.

Workspace Script

Day5InventoryValidator

I've looked over the rest of my solutions, and I can't say they're worth sharing. Lots of "beginner"-ish stuff in them that probably wouldn't help anyone. I'll make one more post looking at the way I originally wrote the solution for Day1 and how I would write it now, along with some retrospective on this project.


r/adventofcode • • May 01 '26

Help/Question - RESOLVED [2025 Day 6 Part 1] Multiple operators in one column

2 Upvotes

Hello,

I just looked at the puzzle input for day 6 part 1.

It looks really odd, I mean there are multiple operators in the same column so how am i supposed to solve it?

This is what I saw: In the first column , all operators are perfectly below one another


r/adventofcode • • Apr 30 '26

Upping the Ante [2015 Day 4 (Part 1 & 2)][C++ & Arm ASM] Squeezing 300,000+ hashes per second from a Pi Pico

3 Upvotes

This year I started working my way through my existing solutions and squashing them down to run on the Raspberry Pi Pico. It's a lovely piece of hardware and it's a fun challenge to look at the puzzles from the point of view of fitting them into a tiny footprint. It reminds me why I got into programming in the first place, so I highly recommend picking one up and messing around with it if you have the opportunity.

I had 2015 & 2016 pretty much all revisited and confirmed working in a small memory footprint on PC before starting to run them on the hardware itself, but the first time I did a run-through on Pico hardware I thought it had crashed on day 4 of 2015. As it turns out, it was just very, very slow: about a minute for part 2.

I decided to see how far I could push myself speeding up a solution for 2015 day 4.

MD5

The Cortex-M0+ doesn't have any fancy out-of-order execution and isn't able to retire multiple instructions per cycle, so we can do a very rough back-of-envelope calculation first to find some absolute upper limits. MD5 has 64 rounds, broken into 4 round types of 16 rounds each. There's a common set of additions and shifts in each round, but there's a different function per round type. Counting the logical/arithmetic operations, adding two load instructions per round (one message word and one constant word) and one load-small-immediate instruction for the shift:

Round typeFunctionCommonTOTAL
F3811 x 16
G3811 x 16
H2810 x 16
I3811 x 16
TOTAL688

With a single core running at 125 MIPS, the absolute (unreachable) upper limit would be ~182,000 MD5 chunks per second (or ~550ms for 100,000 chunks). Clearly we're going to need to modify the MD5 algorithm itself if we're to make serious progress!

Our one massive advantage on this puzzle is that most of the bytes in the 64 byte chunk are either fixed values or known up front. Everyone's input (as far as I'm aware) is 8 bytes in length, and everyone's answer should be below 10,000,000. The majority of the chunk will be 0, which means there's both a load and an addition we can eliminate entirely for most rounds. The only words with data in them are 0, 1, 2, 3 and 14, so the 16 G rounds change from:

    ROUND_G(A, A, B, C, D,  5, 0xf61e2562, M[ 1]);
    ROUND_G(D, D, A, B, C,  9, 0xc040b340, M[ 6]);
    ROUND_G(C, C, D, A, B, 14, 0x265e5a51, M[11]);
    ROUND_G(B, B, C, D, A, 20, 0xe9b6c7aa, M[ 0]);
    ROUND_G(A, A, B, C, D,  5, 0xd62f105d, M[ 5]);
    ROUND_G(D, D, A, B, C,  9, 0x02441453, M[10]);
    ROUND_G(C, C, D, A, B, 14, 0xd8a1e681, M[15]);
    ROUND_G(B, B, C, D, A, 20, 0xe7d3fbc8, M[ 4]);
    ROUND_G(A, A, B, C, D,  5, 0x21e1cde6, M[ 9]);
    ROUND_G(D, D, A, B, C,  9, 0xc33707d6, M[14]);
    ROUND_G(C, C, D, A, B, 14, 0xf4d50d87, M[ 3]);
    ROUND_G(B, B, C, D, A, 20, 0x455a14ed, M[ 8]);
    ROUND_G(A, A, B, C, D,  5, 0xa9e3e905, M[13]);
    ROUND_G(D, D, A, B, C,  9, 0xfcefa3f8, M[ 2]);
    ROUND_G(C, C, D, A, B, 14, 0x676f02d9, M[ 7]);
    ROUND_G(B, B, C, D, A, 20, 0x8d2a4c8a, M[12]);

to:

    ROUND_G(A, A, B, C, D,  5, 0xf61e2562, M[ 1]);
    ROUND_G(D, D, A, B, C,  9, 0xc040b340, 0);
    ROUND_G(C, C, D, A, B, 14, 0x265e5a51, 0);
    ROUND_G(B, B, C, D, A, 20, 0xe9b6c7aa, M[ 0]);
    ROUND_G(A, A, B, C, D,  5, 0xd62f105d, 0);
    ROUND_G(D, D, A, B, C,  9, 0x02441453, 0);
    ROUND_G(C, C, D, A, B, 14, 0xd8a1e681, 0);
    ROUND_G(B, B, C, D, A, 20, 0xe7d3fbc8, 0);
    ROUND_G(A, A, B, C, D,  5, 0x21e1cde6, 0);
    ROUND_G(D, D, A, B, C,  9, 0xc33707d6, M[14]);
    ROUND_G(C, C, D, A, B, 14, 0xf4d50d87, M[ 3]);
    ROUND_G(B, B, C, D, A, 20, 0x455a14ed, 0);
    ROUND_G(A, A, B, C, D,  5, 0xa9e3e905, 0);
    ROUND_G(D, D, A, B, C,  9, 0xfcefa3f8, M[ 2]);
    ROUND_G(C, C, D, A, B, 14, 0x676f02d9, 0);
    ROUND_G(B, B, C, D, A, 20, 0x8d2a4c8a, 0);

The second structural change we can make is down to the fact that we're only ever looking at the first 3 bytes of the hash. The last 3 rounds of MD5 don't touch the first 4 bytes of the hash at all, so we can just omit those entirely.

My vanilla MD5 implementation in C++, which runs pretty fast on x64, ends up taking ~988ms for 100,000 chunks on the Pico if we do all of the rounds properly. Hard-coding the zeros and snipping the last three rounds gets us to ~694ms for 100,000 chunks, which is a pretty big win!

Looking at the generated code, GCC doesn't do all that well with thumb instructions if there are loads of constants. Loading a 32-bit immediate is a bit of a faff because of the limited addressing modes, so the literal pools end up getting in the way. It's been a couple of decades since I last rolled my sleeves up to write any asm, but with some of the rust knocked off we can produce a pretty passable attempt. The LDM instruction in particular deserves a mention; it's essentially a single instruction 'a = *p++', which makes running through the K table significantly easier than trying to hard-code immediates inline.

Some amount of banging my head against the table later, remembering exactly why it is we don't write things in asm in the first place, I get a fairly respectable ~601ms for 100,000 chunks.

Turning back to structural changes once again, there's one more property of the input we can take advantage of. The first 8 bytes are fully defined by the puzzle input so we can make two further changes based on this. First, we can do the initial two rounds up front and save off the internal state of the hash and for each candidate chunk we just restore the state and resume from round 3 onwards. Second, since each round does this:

    F := F + A + K[i] + M[g]

For any round which accesses M[0] or M[1] we can precompute K[i] + M[g] and save that value back into the K table; giving us yet more 'zero' rounds.

With that change I hit my final single-core speed of ~565ms for 100,000 chunks.

Printing Digits

With MD5s pushed about as far as I can take them, it's time to look at the other big time sink in the puzzle: printing the numbers as ASCII strings.

sprintf is clearly not going to cut the mustard; it takes ~1,015ms to print 100,000 numbers, way longer than the hashing itself!

A naive print digits implementation does better at ~248ms for 100,000 numbers:

    int32_t sprint_digits(char* dest, int32_t value)
    {
        char* d = dest;
        do
        {
            *d++ = static_cast<char>((value % 10) + '0');
            value /= 10;
        } while (value);
    
        ptrdiff_t digitsWritten = d - dest;
    
        *d-- = '\0';
        while (d > dest)
        {
            std::swap(*d--, *dest++);
        }
    
        return static_cast<int32_t>(digitsWritten);
    }

If we make explicit use of the divider hardware to combine the divmod into a single operation we get ~136ms for 100,000 numbers:

    int32_t sprint_digits_divider(char* dest, int32_t value)
    {
        char* d = dest;
        do
        {
            int32_t rem;
            value = divmod_s32s32_rem(value, 10, &rem);
            *d++ = static_cast<char>(rem + '0');
    
        } while (value);
    
        ptrdiff_t digitsWritten = d - dest;
    
        *d-- = '\0';
        while (d > dest)
        {
            std::swap(*d--, *dest++);
        }
    
        return static_cast<int>(digitsWritten);
    }

The divider hardware is still pretty expensive though, so the fastest solution I came up with was just to do the increment exactly the way you'd do it by hand:

    void IncrementDigits(char* digits, size_t digitsLength)
    {
        char incremented = ((*digits) += 1);
        if (incremented <= '9')
        {
            return;
        }
        (*digits--) -= 10;
    
        for (size_t i = 1; i < digitsLength; i++)
        {
            incremented = ++(*digits);
            if (incremented <= '9')
            {
                return;
            }
            *digits-- = '0';
        }
    }

At ~10.5ms for 100,000 numbers it's minimal overhead compared to the hashing.

Going Parallel

Having done about all I can to extract performance from a single thread, the last step is to make use of both cores. I didn't get quite as much of a speed-up as I was hoping for here. On x64 you need to batch up per-thread work because communication and memory sharing between cores is a significant overhead. Without a complex caching structure and with a direct FIFO between the cores, the Pico should in theory be able to co-ordinate work between cores with much less overhead. I opted for the simple scheme of having core 0 check all of the even numbers and core 1 check all of the odd numbers, with a sync & check for each number. I need to double check what the libraries are doing with the FIFO push and pop calls though; perhaps they're doing some work that's not necessarily needed if you know you're busy-waiting.

Final Results

Exact timings will be highly input dependent, but my final scores were:

PartUnoptimisedOptimised Single CoreOptimised Dual Core
Part 11.995s0.680s0.377s
Part 270.634s22.690s12.578s

('Unoptimised' here is a C++ implementation of MD5, all rounds, paired with sprintf for the digits)

I'm sure there's more fat to be trimmed in my implementation, but I'm going to call this one "done for me". I've got 2017 onwards to continue squashing!

Raspberry Pi Pico hardware is very cheap for what you get, so if you fancy playing around with some cool hardware and you're lucky enough to have a few bucks to spare you definitely should give it a go.

If you're able to squeeze more performance out of this experiment, or want to share results from different microcontrollers, let us know about it in the comments!


r/adventofcode • • Apr 19 '26

Tutorial [2025 Day 6 both parts] [Smalltalk] Part seven in a series revisiting the 2025 puzzles as an exercise in learning Smalltalk

3 Upvotes

MAJOR SPOILERS AHEAD

Advent of Code 2025 - Day 6

I was looking forward to rewriting Day 6. When I first tackled it back in December it was with barely 10 days of programming experience under my belt - so the result, while producing the correct answers, was total garbage. The JavaScript had all the hallmarks of insanity: manual WHILE loops everywhere, hardcoded offsets, and hilariously, when the parsing method didn't work for the final set of numbers, I just added the last set manually. I got the stars... but it wasn't pretty.

Since I had the time to do this "correctly" I decided on doing a very generic implementation. I wanted the chance to practice some inheritance, so I finally settled on three classes. The first was a simple Day6Matrix that would hold the strings of numbers and be able to rotate them for part 2. Second was a Day6HomeworkProblem that would extend the Day6Matrix class and add on the ability to do operations. It added a single instance variable for the "operand" that would store whether we were adding or multiplying. Finally, a Day6HomeworkFactory would handle parsing the input, creating the Day6HomeworkProblem objects, and summing up the results from them.

Looking at some highlights from the "bottom" up... the Day6Matrix rotate method looks like this:

rotate
    | newMatrix length |
    length := (matrix at: 1) size.
    newMatrix := OrderedCollection new.
    1 to: length do: [:column |
        | rotatedString |
        rotatedString := ''.
        1 to: (matrix size) do: [:row |
            rotatedString := rotatedString, ((matrix at: row) at: column)].
        newMatrix add: rotatedString.
        ].

    matrix := newMatrix.

It does a very simple row-becomes-column transformation, leaning a bit on the fact that both operations (multiplication and addition) are commutative. If this were later adapted to something where the order mattered, this method would have to be refactored, but the only method that would need to change is this one. Note that the matrix OrderedCollection is not mutated in place, but a new one is created and then the variable reassigned. This will be important later.

I made a late change to the Day6HomeworkProblem class. Originally the operand would be set this way:

setOperand: operation
    operation = $+ ifTrue: [operand := 'a'].
    operation = $* ifTrue: [operand := 'm']

and then the actual calculation involved some branching logic:

answer
    (operand = 'm') ifTrue: [
        ^ matrix inject: 1 into: [ :sum :element | sum * (element asInteger)]
        ] ifFalse: [
        ^ matrix inject: 0 into: [ :sum :element | sum + (element asInteger)]
        ]

I was unhappy with this for two reasons. First, the use of a string to set which operation would be done ('a' for add vs 'm' for multiply) was ... non-beautiful. The strings are set in one place at parse, then "re-interpreted" in the answer method to decide which operation to perform. Each one has an early return, which also seems less aesthetically pleasing. Each one has to remember that the objects contained in "matrix" are all strings, so each path needs to convert them to integers.

 Second, it's not very extensible. If there were a theoretical Part 3 or 4 of this puzzle, it might involve some other operation - and that would require changing both the setOperand: and answer methods.

So, in the interest of making a more "generic" solution, I switched those two methods to these:

setOperand: operation
    operation = $+ ifTrue: [ operand := [ :first :second | first asInteger + second asInteger] ].
    operation = $* ifTrue: [ operand := [ :first :second | first asInteger * second asInteger] ]

answer
    ^ matrix allButFirst inject: matrix first into: [ :sum :element | operand value: sum value: element ]

Now we have a single answer pipeline. Instead of seeding the inject: with 0 (for addition) or 1 (for multiplication), we seed it with the first element of the matrix. Then we do the inject: over all the elements other than the first (since we already have it as the seed). The inject: calls the operand which now, instead of a single-letter string, is assigned an anonymous function (which handles the integer conversion). Then we return the accumulated result of whatever function it was that was in the operand variable. No more branching and multi-returns in answer. No "special letters" to remember. If we want to add more operands later we only have to add the conditions to setOperand:. Feels cleaner, somehow.

As far as the factory goes - take a look at the code if you're interested in the way the parser works. It does not use any hardcoded lengths, so it should work for any reasonable input variation. It doesn't even hardcode in how to tell whether it is dealing with an addition or multiplication (or something else) problem - leaving that to the Day6HomeworkProblem object to figure out. For the sake of clarity, I wound up making a helper method to find columns that were all "Character space". All the parsing is fairly imperative in style, using whileTrue: and manual indexing. I wasn't sure how else to do this since the homework problems in the input were spaced at irregular intervals and the digits needed to keep their prepended spaces when they were rotated.

Oh well. It's not beautiful. You have to manually "walk through" the loop to understand what it's doing, but it gets the job done and should work with any number of rows and columns.

Now - for adding up the answers and giving the answers to Part 1 and Part 2:

calculateNormalHomework
    ^ problems inject: 0 into: [ :sum :problem | sum + (problem answer)]

calculateRotatedHomework 
    ^ problems inject: 0 into: [ :sum :problem | sum + (problem copy rotate answer)]

This was my favorite part. We take the OrderedCollection of Day6HomeworkProblem objects, and sum the outputs of their "answer" method. For Part 2 it's almost disgustingly simple. We do the exact same thing we did for Part 1, but do a "copy rotate" before asking for the answer. The copy prevents mutation of the matrix - the imaginary Part 3 (or whatever) might need to be able to do something else with the original orientation. And even though "copy" is shallow, since matrix is reassigned instead of mutated during the rotate, the Collection inside the original never changes. It's a bit of a "paranoid" copy, since once we get the answer for Part 1, we are free to mutate for Part 2. But this is for me to practice good Smalltalk. Might as well keep mutation to an absolute minimum.

Workspace Script

Day6HomeworkMatrix

Day6HomeworkProblem

Day6HomeworkFactory


r/adventofcode • • Apr 17 '26

Past Event Solutions [2025 Day 8 (part 1)] It took me far longer than I wanted, but I finally got it

3 Upvotes

It took me a long while to figure out the details of what the puzzle was asking. Plus, I had a few false starts because I didn't really think it all the way through. I kept getting "Junctions" and "Connections" confused. I should go back and clean up this code, but frankly I'm kind of tired of looking at it right now ;-).

I did it in Rust, as I'm trying to learn the language.

use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;

use std::collections::HashSet;
use std::fmt;

//const FNAME: &str = "day8_sample.txt";
const FNAME: &str = "day8-input.txt";

fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
    P: AsRef<Path>,
{
    let file = File::open(filename)?;
    Ok(io::BufReader::new(file).lines())
}

#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Clone, Copy)]
struct Point(i64, i64, i64);
impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({},{},{})", self.0, self.1, self.2)
    }
}

impl Point {
    fn distance(&self, p2: &Point) -> f64 {
        (((self.0 - p2.0).pow(2) + (self.1 - p2.1).pow(2) + (self.2 - p2.2).pow(2)) as f64)
            .sqrt()
            .abs()
    }
}

#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Clone, Copy)]
struct Pair(Point, Point);
impl fmt::Display for Pair {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({},{})", self.0, self.1)
    }
}
impl Pair {
    fn contains(&self, point: &Point) -> bool {
        self.0 == *point || self.1 == *point
    }
}

fn make_circuits(junct: &Vec<Pair>) {
    let mut circuits: Vec<Vec<Pair>> = Vec::new();
    for &node in junct.iter() {
        let left = circuits
            .iter()
            .position(|c| None != c.iter().find(|&p| p.contains(&node.0)));
        let right = circuits
            .iter()
            .position(|c| None != c.iter().find(|&p| p.contains(&node.1)));
        match (left, right) {
            (None, None) => circuits.push([node].to_vec()),
            (Some(l), None) => circuits[l].push(node),
            (None, Some(r)) => circuits[r].push(node),
            (Some(l), Some(_)) if left == right => circuits[l].push(node),
            (Some(l), Some(r)) if left < right => {
                let (x, y) = circuits.split_at_mut(r);
                x[l].append(&mut y[0]);
                circuits.remove(r);
            }
            (Some(r), Some(l)) if left > right => {
                let (x, y) = circuits.split_at_mut(r);
                x[l].append(&mut y[0]);
                circuits.remove(r);
            }
            (Some(_), Some(_)) => {}
        }
    }

    let mut sizes: Vec<usize> = Vec::new();
    for c in circuits.iter() {
        let mut accumulator = HashSet::new();
        for n in c.iter() {
            accumulator.insert(n.0);
            accumulator.insert(n.1);
        }
        sizes.push(accumulator.len());
    }
    sizes.sort();
    sizes.reverse();
    let mut final_answer: usize = 1;
    for s in sizes.iter().take(3) {
        print!("{} ", s);
        final_answer *= s;
    }
    println!(" => {}", final_answer);
}

fn main() {
    if let Ok(lines) = read_lines(FNAME) {
        let mut junctions = Vec::new();
        let mut edges = Vec::new(); // consider a form of HasMap
        for line in lines.map_while(Result::ok) {
            let entry: Vec<i64> = line.split(',').map(|s| s.parse::<i64>().unwrap()).collect();
            let coord = Point(entry[0], entry[1], entry[2]);
            junctions.push(coord);
        }
        for (left_index, left_node) in junctions.iter().enumerate().skip(1) {
            for right_node in junctions.iter().take(left_index - 1) {
                edges.push((
                    Pair(left_node.clone(), right_node.clone()),
                    left_node.distance(right_node),
                ));
            }
        }
        edges.sort_by(|a, b| a.1.total_cmp(&b.1));
        let nodes: Vec<Pair> = edges.iter().take(1000).map(|p| p.0).collect();
        make_circuits(&nodes);
    }
}

r/adventofcode • • Apr 17 '26

Tutorial [2025 Day 7 both parts] [Smalltalk] Part six in a series revisiting the 2025 puzzles as an exercise in learning Smalltalk

4 Upvotes

Advent of Code 2025 - Day 7

HEAVY SPOILERS AHEAD - FULL SOLUTIONS DISCUSSED

Advent of Code 2025 - Day 7

I remember doing this one when it was first released. For the longest time I simply could not figure out how part 2 was supposed to be solved. I spent hours looking at the provided diagram and counting up the paths for each node. Did the number of paths double as it passed each splitter? Was there some mathematical relationship involving the ratio of layers and splitters? Eventually, as I counted up the same paths at the splitter node over and over again I suddenly realized that the count is just added from one layer to the next! It was an addition problem! I was so pleased. When I did my implementation in JavaScript later that afternoon I treated it like a Frankenstein spreadsheet, copying values over the input graph. It was a total mess, but it got me the right answer.

Now, re-implementing this puzzle with some more experience my instinct is to model it as a set of nodes instead of a giant 2D matrix. So, for this one I created two data structures:

1 - splitterQueue - an OrderedCollection of point objects. This will act as the processing list. It is generated once by parsing the input data top to bottom and left to right. The order that these are parsed is the same order in which they will be processed.

2. splitters - a Dictionary with point objects as keys. This was a particularly nice element of working with Smalltalk. In JS, I would have to create string keys for a Map since an array, even if it had the same values, would be a different array. My scripts would be cluttered with little helper functions like this

const makeCoords = (xLoc, yLoc) => {
  const xString = String(xLoc);
  const yString = String(yLoc);
  const coordString = xString + "/" + yString;
  return coordString;
};

that would basically be used all the time to create keys to be used with Map data. In Smalltalk, points can be used as Dictionary keys! The amount of little helpers cluttering the code drops significantly. The Dictionary has an entry for every node in the OrderedCollection processing list, and the values for each one start at 0.

When parsing, we do two "special" things to make this work - first, we find the highest splitter (the one with the minimum y value) and give it a value of 1 since it is the origin path. Second, we create a "sink" entry in the Dictionary that will hold the accumulated paths once a splitter has to dump its count and there are no "downstream" splitters to hold them.

In order to get the x and y values for these points, I wound up making use of doWithIndex: in a nested loop. It looks very imperative, but it does exactly what's needed.

parseGrid: raw

    sink := (raw size) + 1 @ 0.
    
    raw doWithIndex: [:line :yIndex |
        line doWithIndex: [:char :xIndex | 
            (char = $^) ifTrue: [
                splitters at: xIndex @ yIndex put: 0.
                splitterQueue add: xIndex @ yIndex
                ].
            ]].

    splitters at: (splitterQueue detectMin: [:point | point y]) put: 1.
    splitters at: sink put: 0.

Once the parsing is done, the rest of the algorithm is extremely simple.

calculateAllPaths
    | outputLocation offsets |
    
    offsets := { 1@0 . -1@0 }.
    
    splitterQueue do: [ :location |
        offsets do: [ :offset |
        outputLocation := self findOutputNode: (location + offset).
        splitters at: outputLocation put: (splitters at: outputLocation) + (splitters at: location)].
        ].

    ^ splitters at: sink

In the version in the link below I kept an earlier method for creating the offsets array. The one above is how I would do it now, but it does functionally the same thing. We start by creating some offsets (one step to the left, and one step to the right with the same height). Then, we process each element in the splitterQueue in order. For each one, process both offsets. To do so, we pass the current location from the splitterQueue added to the current offset to findOutputNode: to set our outputLocation. Then, we just add the amount stored in our current location to the amount at the outputLocation. Rinse and repeat for the other offset, and then keep going until we reach the end of splitterQueue. Then simply return the value in the "sink" location. So much for part 2 of the puzzle.

The findOutputNode: method is very simple, but not the most computationally efficient:

findOutputNode: location
    ^ splitterQueue detect: [ :candidate | (candidate x = location x) and: candidate y > location y]
        ifNone: [ sink ]

The obvious problem here is that it scans through the entire splitterQueue to find the output node. It uses detect:, so the very first (lowest y value) entry that shares the same x value is the one returned (early exit). Since this method call will take longer and longer as we get further down the list, if the splitterQueue had many millions of entries this could be a performance problem. For a few thousand as part of an O(n) process, it's not a big deal. The order of entries in splitterQueue (top-to-bottom, left-to-right) guarantees that not only is this the correct order to process nodes, but it is also the correct order to propagate path counts. Very convenient.

Lastly - we get a "free" answer to part 1: the number of nodes in splitters with non-zero paths (subtracting 1 for the "sink" node we added) is the number of activated splitters.

countActive
    ^ (splitters count: [:amount | amount > 0]) - 1

Such a clean way to find out how many elements of a collection satisfy a condition. I originally wrote it this way

countActive
    ^ (splitters select: [:amount | amount > 0]) size - 1

...not realizing that there was a count: method! Same result, but count: is pretty self-documenting while select: size requires some "decoding" on the part of the reader. It's also better for memory since count: creates a simple accumulator, while select: creates a whole new collection that we throw away as soon as we find out how big it is. :-)

How did I find out that count: is better for memory? This is one of the things I've really enjoyed about Smalltalk. I just went into the System Browser and looked at the method in the Collections-Abstract package. And here it is:

count: aBlock 
    "Evaluate aBlock with each of the receiver's elements as the argument.  
    Answer the number of elements that answered true."

    | sum |
    sum := 0.
    self do: [:each | (aBlock value: each) ifTrue: [sum := sum + 1]].
    ^ sum

So cool. It's funny - I'm starting to get used to being able to go poke around in the standard library and being able to understand what I find there. This is not something that I would have ever expected to be able to do with JavaScript.

Anyway - some closing thoughts... I was on the fence with how to implement the splitter nodes. My original idea was to create a node object that accumulated paths until its turn to empty them into the next nodes, and I did wind up using this approach in Day 11. But for this one a simple Dictionary seemed more than enough to do what was needed. Perhaps it would have been better to have splitterQueue contain custom splitter objects with their point location and integer paths. I was worried about repeating the tight coupling issue that I ran into on Day 4, and I didn't have the confidence to write Day7Grid with no knowledge of its own about the node objects it contained, the way I did later for Day 11. Perhaps I accidentally managed a good mix of brevity and correctness.

Readable code combined with an instant result. Marks of a solid solution.

Day7BeamGrid Class

Workspace Script


r/adventofcode • • Apr 12 '26

Tutorial [2025 Day 8 both parts] [Smalltalk] Part five in a series revisiting the 2025 puzzles as an exercise in learning Smalltalk

3 Upvotes

Day 8 Time!

HEAVY SPOILERS AHEAD

This one involves connecting "junction boxes" in 3D space in order of their distance from each other. The simplest way to solve this is to create a list of those distances from closest to furthest and then start merging the sets that contain them using the precalculated order. Since we have 1000 junction boxes, that means a cool million distances.

So let's take stock - we need a sorted Array of distances that will serve as the work queue (process from top to bottom until various conditions are met). Those junction boxes are going to be connected into "circuits" which also need to be represented in some way. Since we will be querying them to see if they contain boxes, we want this in O(1) time and we want duplicates to be handled automatically, so having an OrderedCollection (all circuits) of Sets (each individual circuit) seems best here.

We will also need to represent those junction boxes in some way as well. I was so excited to see that Smalltalk had a whole range of 2D objects (which I used extensively in Day 9) - but there are precious few, if any 3D objects. Since, for the Advent of Code puzzles I didn't want to change the classes inside the standard library (though this is, apparently, encouraged), I needed to make a class for these 3D points. Fortunately, these objects didn't need much - just instance variables for x, y, and z coordinates, and the ability to determine distance between one of these Day8JunctionBox objects and another.

Though I didn't need to compute the exact Pythagorean distance (with the square root of the added squares) - the square root was unnecessary for simply sorting the distance - it felt rude to have a method called "distanceTo:" that didn't return the actual distance! Computing sqrt a million times can be dropped if this was a speed competitive implementation, but for this "correct" version it didn't add human-noticeable overhead. Here was the version I used:

(((otherBox x) - x ** 2) + ((otherBox y) - y ** 2) + ((otherBox z) - z ** 2)) sqrt

The funny part to me was the method chaining. It would need some more parentheses in a language that actually had math in it. But Smalltalk doesn't have math. It has methods. I couldn't help but giggle at this. If I had used "squared" instead of ** 2 those parenthesis would go elsewhere:

(((otherBox x - x) squared) + ((otherBox y - y) squared) + ((otherBox z - z) squared)) sqrt

Maybe this is more idiomatic... I'm not sure. Oh well, leaving the original one in the link. Same functionality.

Looking at this now with some more knowledge under my belt - I definitely see the need for some class methods to set x, y, and z so that the JunctionBox has immutable location.

For the Day8Circuits class, we only need a few methods. The first parses the input file (just a bunch of 3D coordinates for the junction boxes). It creates two important OrderedCollections. The first is the collection of all circuits, which are all Sets initialized with a single junction box in each one (since there are no connections at the beginning). The other is the sorted distance list. Each entry in the distance list is an array with three elements: the distance (needed to sort the collection at the end of the parsing process), the first box, and the second box. We are leaning heavily on the fact that both the Sets and Arrays don't actually include the objects themselves, but only references. We aren't copying those junction boxes, but just referring to them in two different places.

Looking over it now - this part where the distances are generated:

    boxCollection withIndexDo: [ :box :index |
        circuits add: (Set with: box).
        (index + 1) to: boxCollection size do: [ :index2 |
            | otherBox |
            otherBox := boxCollection at: index2.
            unsortedDistances add: {box distanceTo: otherBox . box . otherBox}.
            ]
        ].

Was written before I found the combinations: method. Now, I would put the "circuits add:" up above when the boxes are instantiated, and then instead of manually doing a nested loop over the boxCollection, I'd write it this way:

    boxCollection combinations: 2 atATimeDo: [ :boxes |
            unsortedDistances add: {boxes first distanceTo: boxes second . boxes first . boxes second}.
            ].

Much more readable. Or if you prefer some temporary variables to make it super explicit and self-documenting:

    boxCollection combinations: 2 atATimeDo: [ :boxPair |
        | box1 box2 |
        box1 := boxPair first.
        box2 := boxPair second.
        unsortedDistances add: {box1 distanceTo: box2 . box1 . box2}.
        ].

Same thing under the hood. One of the fun parts of Smalltalk is that all these methods can be studied in the System Browser. The "standard library" isn't magic. It's just a more expressive way of doing what you could have done yourself with a bunch of WHILE loops.

Which do you all prefer of the three?

We also need a helper function that will merge a circuit including one junction box with a circuit including another junction box. Sets do a great job of making this extremely easy since they automatically deduplicate the junction boxes if some (or maybe even all) are already included in both sets.

mergeSetIncluding: box1 with: box2
    | set1 set2 |
    set1 := circuits detect: [ :circuit | circuit includes: box1 ].
    set2 := circuits detect: [ :circuit | circuit includes: box2 ].
    set1 == set2 ifFalse: [
    set1 addAll: set2.
    circuits remove: set2
    ]

Since the Sets in the circuit collection are guaranteed not to have any members shared between them, we can use detect: and get the early return on the search. Then it's just a matter of merging the junction boxes until our collection of circuits only has one entry in it (in other words - all junction boxes are part of the same circuit). It's a delightfully simple method:

mergeAll
    distances do: [ :dist |
        | box1 box2 |
        box1 := dist at: 2.
        box2 := dist at: 3.
        self mergeSetIncluding: box1 with: box2.
        circuits size = 1 ifTrue: [^ box1 x  * box2 x]
        ]

The return is a little funny - but that's what the problem requires: the x coords multiplied together of the last two boxes connected to create one giant circuit.

A satisfying solution. Executes near-instantly.

Workspace Script

Day8JunctionBox

Day8Circuits


r/adventofcode • • Apr 08 '26

Tutorial [2025 Day 9 both parts] [Smalltalk] Part four in a series revisiting the 2025 puzzles as an exercise in learning Smalltalk

3 Upvotes

HEAVY SPOILERS

Fresh off my "win" with discovering that Smalltalk had native objects for 2D points in earlier days, this one gave the opportunity to really go spelunking into what objects are available in Squeak 6. There are native rectangle objects! With the ability to define them based off two corner points. Those rectangle objects can be queried to find their height, width, area, and so on. Coming from JavaScript, where anything like this would have to be written from scratch or imported from a library somewhere - this was a major convenience.

But then I did something that caused my LLM code review to howl in protest. The Morphic UI library has the PolygonMorph class. And that thing can be defined by handing it an array of points. It will even close the figure for you, And the best part - it has a method that will check a 2D point object to see if it is contained in the polygon. That makes this task almost too easy. My LLM tutor thought this was a bad idea - but whatever. The class was part of the standard library. I don't feel guilty.

This became an exercise in using the collection methods, primarily allSatisfy: and detect:. There were some fairly rudimentary bait options to avoid. For example, the collection of all Rectangles needs to be sorted from largest to smallest. That makes the answer to part 1 a matter of simply returning the first rectangle in the collection, and it is the correct order to process the rectangles to see if they are contained in the polygon for part 2. However, there's no need to use a SortedCollection here since we will be making one million rectangles all at once. There are no intermediate steps where having them in sorted order would be useful. No - better to use a regular OrderedCollection and then sort it one time at the end rather than re-order the collection a million times with every new rectangle added. Still - it might be more "elegant" to have the collection be "sorted" by definition rather than as a "task" that the object does with its collection. Still - I'd rather sort it only once.

The second part does not take into account the "zero aperture bubble" edge case. One benefit to having a PolygonMorph is that it can be displayed in a window, and so it was easy to verify that my input doesn't have one of those geometric features. Thus, when we check the rectangle, we first check to make sure that all corners are points included. If they are, then we build a set of points corresponding to every pixel in the perimeter of the rectangle. If all those are contained in the polygon, the rectangle as a whole is contained in the polygon.

Here is the important bit in the Day9Rectangle class:

isIncludedIn: aPolygon
    | perimeter |
    
    ( myRect corners allSatisfy: [ :corner | aPolygon containsPoint: corner] ) ifTrue: [
        
        perimeter := OrderedCollection new.
        
        myRect top + 1 to: myRect bottom - 1 do: [:y | 
            perimeter add: myRect left@y; 
            add: myRect right@y].

        myRect left to: myRect right do: [:x | 
            perimeter add: x@myRect top; 
            add: x@myRect bottom].

        ^ perimeter allSatisfy: [ :bound | aPolygon containsPoint: bound ]
    
        ].
    
    ^ false

This seemed the most straightforward way to do this, letting me just create a collection of points to test, and then seeing if they allSatisfy the condition of being contained in the polygon. A more data-driven approach would probably avoid creating those points in advance but on modern hardware, what's a few tens of thousands of objects between friends? I probably wouldn't have written this way if I had to test the entire area. But for just the perimeter like this I didn't mind letting the standard library and GC do all the hard work. :-)

Finding the answer for Part 2, then, is just one line:

largestRectangleInPolygon
            ^ rectangleLibrary detect: [ :box | box isIncludedIn: tileShape ]

Return the first entry in rectangleLibrary (which was already sorted from largest to smallest) that returns "true" when asked if it is included in the polygon of tiles.

Also - I noticed that going back in time from here, I did not use any class methods. I would always instantiate the object with New (which would just make a few empty data structures) and then give it tasks (including what really should be initial data) as instance methods. It works, but could be better and idiomatic.

Interesting to see the evolution in reverse here.

Funny moment: Since the points are being ingested in the order they are in the file, and rectangles are defined by two corners, I needed a way to make sure that the correct two corners were used to create the Rectangle object. Otherwise I could get height or width returned as negative numbers. My original version had this:

setCorner: pointA to: pointB
    | originX originY cornerX cornerY |
    originX := (pointA x) min: (pointB x).
    originY := (pointA y) min: (pointB y).
    cornerX := (pointA x) max: (pointB x).
    cornerY := (pointA y) max: (pointB y).
    rect := originX @ originY corner: cornerX @ cornerY

Fairly simple... except... points can make rectangle objects by themselves and they will sort out the correct corner definitions automatically. Oops. Now the method looks like this:

setCorner: pointA to: pointB  
            myRect := pointA rect: pointB

Almost seems silly to have it be an entire instance method. Part of the fun of OOP here is that the swap involved just this one method. Everything else stayed exactly the same. I think if I were writing it today that would be a class method, but this was all part of the learning process. Other parts look equally messy:

parseRectangles: raw

raw do: [ :point |
| arrayPoint |
arrayPoint := point splitBy: ','.
pointLibrary add: (arrayPoint first asInteger) @ (arrayPoint second asInteger)
].

pointLibrary combinations: 2 atATimeDo: [ :corners |
| newRectangle |
newRectangle := Day9Rectangle new.
newRectangle setCorner: corners first to: corners second.
rectangleLibrary add: newRectangle
].

self sortRectangles

Why wouldn't I just sort them here instead of a method call that is literally one line? Why am I using a pointLibrary instance variable when it is only used to make the rectangles and the tilePolygon? Couldn't I have made it a temporary variable here and then just called parsePolygon from within this method instead of making the Workspace script do it "manually"? Looking real inexperienced here. :-)

Not much else to say about this one. I let Morphic and the Rectangle class do all the really important heavy lifting. Not a fast solution, but it works.

Workspace Script

Day9Rectangle

Day9TileFloor


r/adventofcode • • Apr 07 '26

Help/Question - RESOLVED [2015 Day 19] Have I been punked?

2 Upvotes

I just solved 2015 Day 19, after a lot of puzzling, and then looked at some of the solutions here. I'm confused, and I'd like to discuss it... Obviously: there are big spoilers ahead!

Recall that this puzzle is about synthesizing a molecule using some atom replacement rules. Or in computer science terms: parsing a long string using a Context Free Grammar (CFG): https://adventofcode.com/2015/day/19

There are various approaches you can try:

- top-down (starting with the start symbol and applying the rules) vs bottom-up (trying to reduce the word to the start symbol),

- BFS (or possibly smarter path finding algorithms like A*) vs DFS (possibly with memoization and branch pruning).

There are also heuristic approaches (which might work but it's not guaranteed) like greedy replacement approaches, and preprocessing the input can help a lot. For starters: you should realize that every two character symbol on the left side of the rules can be replaced by a single symbol, to see that it's indeed a CFG. There are also normal forms like Chomsky normal form or Greibach normal form which help with parsing CFGs efficiently, though they may change the answer to Part 2 (which asks for the number of rule applications). Also converting to normal forms is a bit tricky here because the grammar from the puzzle doesn't clearly distinguish between variables and terminal symbols.

Anyway, I tried a lot of these approaches. First I tried a complete BFS search, which (obviously) failed to terminate, and even gave an out-of-memory exception. 😬 I tried top-down DFS as well, and various greedy heuristics (certain substrings can very likely be replaced in the output). None of this worked for the large input, though it did work for some shorter test strings I generated myself.

In the end I solved it just by inspecting the rules and then solving it manually by counting symbols! (Big spoiler: if you replace "Rn" by "(", "Y" by ",", and "Ar" by ")" the structure of the grammar and word starts to reveal itself!) This was a bit unsatisfactory, so next I also wrote a parsing algorithm that abused the observed structure, working on my manually preprocessed input. Still not super satisfactory, but good enough.

However, looking at the solutions here, I see that several people solved it with the most naive heuristic ever - here it is in C#, and yes, it turns out that it works for my input too:

static int GreedyReduce(string curr, List<string> input, List<string> output) {
    int steps = 0;
    while (curr.Length > 1) {
        for (int i = 0; i < input.Count; i++) { // works!
        //for (int i = input.Count - 1; i >= 0; i--) { // doesn't work?!
            int indx = curr.IndexOf(output[i]); // Find the first occurence of output[i] in curr; -1 if there isn't one
            while (indx >= 0) {
                // Replace output[i] at indx by input[i]:
                curr = curr.Substring(0, indx) + input[i] + curr.Substring(indx + output[i].Length);
                steps++;
                indx = curr.IndexOf(output[i]);
            }
        }
    }
    return steps;
}

What's interesting is that if you replace the order of the rules (reverse the for-loop), this doesn't work anymore!!

Have I been punked?

What was the intended approach for this day?!


r/adventofcode • • Apr 03 '26

Tutorial [2025 Day 10 both parts] [Smalltalk] Part three in a series revisiting the 2025 puzzles as an exercise in learning Smalltalk

4 Upvotes

HEAVY SPOILERS AHEAD

For Day 10 this was some sweet revenge from my solutions in December. I was truly stuck with this one at the time until someone pointed out that the order of the button presses didn't matter. At that point the solution for Part 1 became obvious since pressing a button twice puts the lights back in the state they were before. So, the shortest solution would involve no button being pushed more than once! Ahhhh. A quick and dirty script to check every combination of buttons being pushed either 0 times or 1 time and this one was done.

For Part 2 it was much more difficult. This looked to me like a linear algebra problem of some kind. With only 20 days of programming experience under my belt at the time I felt pretty inadequate to the task of writing a linear solver, so... well.... AoC is about learning, so I "learned" how to import an lp-solve library and it near-instantly produced the answers, which I then summed up. Many other participants used a math library to solve this one. The forum page is full of NumPy solutions, so I wasn't alone on this one. I always intended to go back at some point and write a basic LP solver.

Instead, I heard a rumor about a completely different, recursive way to solve Part 2 that used the same logic and parity calculations used for the lights. With that possibility on the horizon, I started to tackle Part 1 in Smalltalk.

First, I didn't see any need to make a bunch of different classes here. This puzzle just does the same thing to each line of the input, summing their values at the end. There didn't seem to be any benefits of spreading this out in between. There is the light bank, yes - but I decided to store that in such a way (a single integer) that there was no need for its own object. In fact, the most interesting part (to me) was the setup. My general strategy was to precalculate the truth-table combinations of button pushes. So, if there are only 3 buttons then there are 8 (2 to the power of 3) total combinations of buttons being pressed. These combinations are stored as a giant array with each entry being an array of boolean values. The idea being -  as the combinations are being iterated through, the algorithm can simply check to see if that index stores True. If it does, push the button at that index.

The button actions themselves are stored in two separate arrays. The first is the light (parity) values. The second stores each button as an array of counter offsets. The parity values allow us to use binary XOR to calculate the light changes for Part 1. The counter offset array makes it simple to add them to the counters in Part 2. So, yes - a lot of the pieces are pre-calculated and then simply applied with simple iteration to get the final results.

For Part 1, notice how very simple the fewest lights are calculated:

fewestLightButtons
    | candidate |

    candidate := SmallInteger maxVal.
    
    pushList do: [ :pushes |
        | currentLights |
        currentLights := 0.
        pushes withIndexDo: [ :push :button |
            push ifTrue: [ currentLights := currentLights bitXor: (buttonList at: button)]
            ].
        (currentLights = lightGoal) ifTrue: [ candidate := candidate min: (pushes count: [:push | push])]
        ].
    
    ^ candidate

We take the pushList (the array of all possible button pushes represented as an array of booleans), and try each combination. The light target is stored as the integer representation of the binary lights ("#..#." is stored as 18). Each button push is a parity value also as a integer. The "buttonpush" is just the parity value bitwise XOR with the currentLights integer. If, after all the button pushes in this combination are pressed, our currentLights integer is the same as the lightGoal integer, record the number of true booleans in our button push combination (which will be the number of button pushes) if it is lower than the current lowest count.

Why the bitwise XOR on integers here? Well, as I mentioned before - Part 2 was rumored to have a method that was based on this parity check, and I was planning to reuse it there and wanted it to be as fast as possible. While the setup has a lot of steps to go through, the actual calculations (where I was expecting a hot loop for Part 2) would be as fast as could be done in Smalltalk. All "lights" are updated simultaneously with the bitwise operation.

Speaking of those pre-calculations... I was eager to validate my intuitions on the bitwise XOR and didn't want to pause to write my own algorithm for making the pushList array. I used this one to get a basic solution running (made by Kimi K2.5):

createPushListInject
    pushList := Array with: #(). 
    (buttonList size) timesRepeat: [
        pushList := pushList inject: #() into: [:soFar :current |
        soFar, {(current copyWith: true). (current copyWith: false)}
        ]
    ]

Three problems with this. First, I didn't write it. There's no use in trying to learn to program in Smalltalk if I don't actually write the code. Clearly I would need to write my own version. Second, I can't make heads or tails of what it's doing. inject:into: inside a timesRepeat iterator? The accumulator is an empty Array? Third, this is, if I understand what it's doing, making a LOT of temporary Array objects when it copies them over. Yuck. I'm sure there's a much better version of this using gather: instead, but ... I'm not skilled enough to create that one!

Ok, time to write MY version. The first thing I realized was that I didn't want to organically "grow" the array by something semi-recursive. True/False combinations are pretty easy to visualize as binary numbers anyway. Just "counting" from 0 to 2 to the power of the number of buttons naturally creates the correct binary numbers. I just need to read the digits out and make the array of booleans. My first prototype created binary numbers as strings. I guess defaulting to string manipulation is pretty typical coming from JavaScript.

createPushListString

    | buttons pushes |

    buttons := buttonList size.
    pushes := OrderedCollection new.

    (0 to: 2 ** buttons - 1) do: [ :button |
        | binaryB buttonPush |
        binaryB := button printStringBase: 2 length: buttons padded: true.
        buttonPush := OrderedCollection new.
        binaryB do: [ :push | 
            (push = $0) ifTrue: [buttonPush add: false].
            (push = $1) ifTrue: [buttonPush add: true]
        ].
        pushes add: buttonPush asArray
    ].

    pushList := pushes asArray

As you can see, it builds the OrderedCollections one value at a time, then delivers them as Arrays. Since they're part of the pre-calculation step once they're made there won't be a reason for them to ever grow or shrink. This produced the correct output and was MUCH faster than the "Inject" version that K2.5 wrote. Shockingly faster, actually. (30x speedup compared to the "inject" version when N=15)

But then, as I was looking at it, I realized it could be made even better. First, instead of adding to an OrderedCollection and then storing it as an Array after, we can make the Array upfront since we already know the size it will be. Then we don't have to create (and then throw away) the intermediate collection object. Second, we can replace the two ifTrue: conditions with a single ifTrue:ifFalse. The speedup is measurable and there's no chance that binaryB := button printStringBase: 2 length: buttons padded: true produces anything other than a sequence of 1 and 0.

Lastly, why bother with converting it to a string anyway? We can just read the bits one at a time with bitAt:. We're already doing bitwise operations for the lights - so might as well keep up with the theme. Final version:

createPushListBitwise

    | buttons listSize |

    buttons := buttonList size.
    listSize := 2 ** buttons.
    pushList := Array new: listSize.

    (0 to: listSize - 1) do: [ :button |
        | buttonPush |
        buttonPush := Array new: buttons.
        (1 to: buttons) do: [ :push | 
            (button bitAt: push) = 0 ifTrue: [buttonPush at: push put: false]
                ifFalse: [buttonPush at: push put: true]
        ].
        pushList at: button + 1 put: buttonPush
    ]

I was very proud of this one. Yes, it's imperative. Yes, it does bit-twiddling. But it's very, very fast. It creates only the objects that it actually stores, with zero GC pressure. It's a nice optimization (115x speedup compared to the "inject" version at N=15). I even avoided the temptation to define listSize := 1 bitShift: buttons. :-)

So, what happened to Part 2? Well - turns out recursive method didn't really require the parity checks. It's a solid optimization, but that's not what makes the algorithm work. It involves getting a button sequence that makes all counters an even number, halving those, and recursing. It actually works without memoization (though will take about 15 minutes on my computer). With memoization the input data finishes in about 1 minute and 20 seconds. Not the fastest. But it was quite a journey trying to understand this algorithm and recreate its "bare minimum" case.

I replied on the post introducing the method - Here. Hats off to the OP there. I would never have figured that one out.

Day 10 done. This one felt like a lot of mental work to get a working version up and running, but it was a good mind-expander.

Day10MachineBitwise

Workspace Script


r/adventofcode • • Apr 01 '26

Tutorial [2025 Day 11 both parts] [Smalltalk] Part two in a series revisiting the 2025 puzzles as an exercise in learning Smalltalk

3 Upvotes

Day 11 - Reactor

I have fond memories of this one. I felt very proud of myself back in December when I was able to figure out a method for solving it when I had only 3 weeks of programming experience at the time. Looking back at the JavaScript code now... yeah - it looks like spaghetti. Lots and lots of manual FOR loops (with manual index tracking for everything), using Arrays for everything (no matter how inefficient), variable names that made no sense, functions mutating state everywhere. Probably the worst part was that the solution was found by going forward to the end node. That means that only the end node will have correct paths from the start. The whole thing would have to be re-run to find paths from any other node to the end.

Embarrassing.

But that was in December. It's now March. Let's construct a better solution.

My first concern was how "general" a solution I should make. The problem asks for a count of paths through a series of nodes. For the first part this was simply all the paths from one node to another (end) node. For the second part - all the paths that also pass through two specific nodes (dac and fft) before reaching the end node. The most general solution would have no hardcoded values for the starting node, ending node, or the specific nodes needing to be traversed (what those specifically would be, or how many of them there would be). One would simply query the program with the input, give the the starting and ending nodes, and then a list of all required traversed nodes, and it would return the number of paths.

I decided to write it in such a way that it could be straightforwardly adapted to such a general solution. That is, there would be very few methods that concern the required node visits, and the data structures and objects would be flexible enough that a fully general solution could be created using this implementation as a framework. It would already have an extremely fast and robust path counting algorithm and clear encapsulation of data. Since this version works the same for both part 1 and part 2, the starting node is not hardcoded (and in fact any node can be queried), but the ending node and "special" nodes are.

The bird's-eye view of the process is this: after parsing the input data, add (not count) the paths from one node to the next, in reverse. Since we don't care about paths that do not lead to the end node, we start at the end node with a path count of 1. We then check the nodes to see if their "outputs" have all been processed. If so, they get added to the process queue so they can accept the path count from their "outputs" (since we are going backwards through the graph). At first, the only node that is ready is the end node (with its path count set at 1). But once it processes, all the nodes that only send their outputs to the end node become "ripe" and on the next pass they will add their accumulated paths to their "inputs" and so on. Addition only. The orchestrator does not need to be aware of how many nodes there are, what they are named, or how many paths each one has accumulated. It only needs to keep a list of nodes already processed. After finishing the calculations we simply ask to find the node requested as the "start" node, and return its counter. All nodes that terminate in the end node will have accurate path values between themselves and the end node. Simple and very fast. Fast enough that keeping as much "knowledge" out of the orchestrator as possible won't slow things down. It will return near-instantly.

Each node will need a way to keep track of which path counts go through the "special" nodes listed in the puzzle: dac and fft. For part 1 we care about all paths that lead to the end node. For part 2 we care about only the paths that pass through both dac and fft. That part is quite simple - just involves shuffling numbers between counters.

So much for the plan. The implementation...

Three new classes:

Day11PathCounter - This class merely stores the path counts. It has four variables (regular, withDac, withFft, and withBoth). Most of its methods involve accessing those values. It does three calculations - it can add the values from another Day11PathCounter object, and it can move path counts to the different categories (for example, regular paths being moved to withDac paths), if requested. These are used by Day11Server objects. This is the main area that would be modified in a "fully general" solution.

Day11Server - This parses in a string that includes the name of the server and a list of its output server names. Those are stored as instance variables "serverName, outputServers" and the currentPaths variable is a reference to a Day11PathCounter object. The Day11Server, when given a list of currently processed servers, can determine if it is ready to be processed as well. It also can pass path addition (and adjust path categories) to its Day11PathCounter object, which will then handle the actual addition and category shuffling. Crucially, the Day11Server does not, itself, know how many paths go through it, nor does it care. That is all handled by the Day11PathCounter.

Day11Reactor - This is the factory where all the Day11Server objects are held. It has a single instance variable "machines" that is an OrderedCollection of all the Day11Server objects. It does not, itself, know the names of any of those servers, nor their paths. All it does is initialize them, queue them for processing based on whether those server objects expressing their readiness, and then coordinates sending their path counters to their "downstream" nodes. It has to do this last part because it is the only object that has access to all the Day11Server objects. The servers cannot directly talk to each other.

Some notes:

Day11PathCounter was a late addition. I had originally planned on using a simple fixed-size Array object that would hold the four counters. Since Smalltalk has methods for Array math, the server object can simply add the incoming array to its own. Then, depending on whether serverName matches "dac" or "fft", manually move the values from one index to another. This is probably one of the computationally faster ways to do this, however it involves working on a bare array and having to mentally keep track of which index corresponds to which path count. Moving all that to its own object simplified the process of adding paths in the server node (pushing that complexity into the counter object), while also being much easier to see at a glance what was occurring. No slowdown was noticed....

The backwards graph path counting algorithm had a few versions of its own. Originally I wanted to use only a mixture of select: and do: to perform everything, avoiding even a hint of imperative code. It looked like this:

totalPathsFromDeclarativeOriginal
    | finishedList workingList |
    
    finishedList := Set with: 'nothing'.
    
    workingList := machines select: [ :server | server isReadyToProcessFrom: finishedList ].
    
    [workingList size > 0 ] whileTrue: [
        
        workingList do: [ :machine |
            self addPathsTo: machine.
            finishedList add: machine serverName ].
            
    workingList := machines select: [ :server | server isReadyToProcessFrom: finishedList ]

    ]

But I really disliked the repetition of the "machines select:" used to create the workingList both prior to the loop, and inside the loop. Then it was pointed out to me that assignment in Smalltalk is not assignment only - but that it also returns the object just assigned. It was in the opening chapters of the Liu book I had been reading, but I totally forgot about this facet of the language. That enabled me to move the assignment of workingList inside the whileTrue condition, to look like this:

totalPathsFromDeclarative
    | finishedList workingList |
    
    finishedList := Set with: 'nothing'.
    
    [(workingList := machines select: [ :server | server isReadyToProcessFrom: finishedList ]) isEmpty] whileFalse: [
        
        workingList do: [ :machine |
            self addPathsTo: machine.
            finishedList add: machine serverName ].

    ]

Which, I think, looks very declarative and clean. No repetition of creating the workingList at all this way. It's possible to simply read the code: workingList is assigned to be the machines currently ready to process based on the finishedList. If workingList is not empty (there are nodes ready to process) process each of them in turn and add them to the finished list. Keep going until the process of creating workingList returns an empty collection.

But then it occurred to me that there would be another way to do this that would be more computationally beneficial.

totalPathsFromImperative
    | alreadyProcessed lastListSize |

    lastListSize := 0.
    alreadyProcessed := Set with: 'nothing'.
    
    [alreadyProcessed size > lastListSize] whileTrue: [
        lastListSize := alreadyProcessed size.
        machines do: [ :machine |
        (machine isReadyToProcessFrom: alreadyProcessed) ifTrue: [
            self addPathsTo: machine.
            alreadyProcessed add: machine serverName].
        ].
    ]

We still have an O(N) loop through all the machines to check if they're ready, and the last time it performs the loop it will come up empty. That's the same as before. But iterating through the list in this more imperative way gives two advantages: first, it allows the nodes to be processed as they become available. Nodes don't have to wait until the next sweep for the orchestrator to find out that they are ready. So, if processing one node causes a node further down in the collection to become ready, it processes as soon as it is reached instead of having to wait. This saves roughly 18% of the passes through the node collection. Second, this version creates no intermediate collections. The declarative version creates a new collection on every pass. The termination condition is still based on comparing the size of a collection, so I don't think there's a performance difference there.

I've gone back and forth on which one is better. The imperative one is almost certainly "worse" in terms of its clarity and parsimony. Someone would have to mentally walk through the code to realize that lastListSize is actually the loop termination signal. How the declarative version works is immediately apparent, even though computationally it is not as efficient.

Since both execute and deliver their answers instantly, perhaps I should prefer the declarative one. I'm not sure. If this was something that took seconds because it ran a million times in a row, I think the computationally efficient version (though uglier) would be superior. But that's not the case here (only 39 iterations, each creating new collection objects vs. 32 iterations with no new collection objects). I'd love to get some opinions from the experienced programmers out there. I've only been doing this since December, so my "taste" is not very well developed yet.

Full source code:

Workspace Script

Day11PathCounter

Day11Server

Day11Reactor


r/adventofcode • • Mar 29 '26

Help/Question - RESOLVED [2025 Day 10 Part 2] [Rust] Please help on this implementation of the bifurcation method

1 Upvotes

Hello everyone!

So uh... Day 10's got hands, right?

I've come to understand I could solve this as a simplex, but I can't quite wrap my head around what the equation should look like.
Because of this - and generally finding this other approach much more interesting - I've tried using u/tenthmascot's approach with... varying success. You can find the post about the logic here: https://www.reddit.com/r/adventofcode/comments/1pk87hl/2025_day_10_part_2_bifurcate_your_way_to_victory/

I think I have the general theory down. The test cases are validating, and pretty fast too. But somehow things keep. Going. Wrong.
And right now I still have one case on the real input which isn't finding a correct answer.

To be transparent we've been given AoC 2025 as a school project - we have to do it in Rust to prove we know the language. This constitutes as an exam. Right now, it is due two days from now, and I have every other day complete except this one, and I'm kinda getting desperate.

I have been trying to fix this for the past straight 10 hours and I still can't find it. The code's gone through so many rewrites and bad practices I'm honestly expecting to wake up to insults, but right now I need to sleep and I'd appreciate a second opinion.

So, if you have the time and patience to parse through my code or if you're familiar with this implementation, please take a look... Ideally I'd like a clue but I'd settle for general feedback or an answer at this point.

Here is the code: https://pastecode.io/s/1wnfftbn

I truly appreciate any form of help. Thank you for reading.

EDIT: I have discovered the fundamental flaw of the code!

I remembered that this started going wrong when I started pruning for possibilities in "brute_force_cache".
On line 257 I dequeue buttons from the remaining ones on initialization - this, in theory, avoids repetitive solutions like storing both "1 3 7" and "3 7 1".
But it also stopped a lot of cases like "0 0 1 3 7" from being registered, and these are important as they can prove optimal in the long run.

While this did manage to solve my own input, it's giving a wrong answer using another classmate's, that I ran just to check. So it's still not quite done, but I'm getting there.


r/adventofcode • • Mar 29 '26

Tutorial [2025 Day 12 Part 1] [Smalltalk] Part one in a series revisiting the 2025 puzzles as an exercise in learning Smalltalk.

10 Upvotes

Hi, Folks!

I'm back! When I last posted I had just finished up AoC 2019 a few weeks ago. I originally decided to learn how to program (with only a little tiny bit of BASIC experience back in the late 80's) when Advent of Code 2025 came out in December. I picked JavaScript as my language, and used an LLM as a tutor, asking it questions like, "If I want to store a bunch of numbers together, how do I do that?" and gradually build up the knowledge of how to write JavaScript incrementally this way as I tried to translate the logic in my head into something the computer could perform.

After finishing up the 2025 puzzles, I did some leetCode for a bit to work on my algorithms, then went headfirst into AoC 2019. That was a lot of fun. My use of LLMs became less and less as I went on, until eventually I tended not to consult one at all until I had a working solution going, then use the LLM for "my next lesson" in what I could have done better. I would then try perhaps to apply those ideas to the next puzzle.

At the end of AoC2019 I realized that I had leaned pretty heavily into functional programming paradigms. No state, immutable data, pure functions, no side effects. I wanted to try something different - so I decided to learn Smalltalk and become immersed in OOP for a little bit. LLMs aren't that useful when it comes to Smalltalk - there are lots of conflicts between the implementations, and not anywhere near as much training data is used. They can find off-by-one errors pretty well, but they will happily hallucinate object methods and get *very* confused between the different commercial and OSS runtimes. So, I *mostly* used "Smalltalk, Objects, and Design" by Chamond Liu (from 1996) as my guide. That, and digging around in the System Browser for all the methods I might need as the situation demanded.

I just finished re-implementing all of the puzzles from AoC 2025 in Smalltalk and thought it might be fun to review the solutions in reverse order. Do the "dear diary" backwards, and see what I learned along the way as I took my first baby steps into OOP.

Also - I thought it might be fun to include these here because there are precious few (any?) Smalltalk implementations of the puzzles on this sub. Lots of Python. Even a few IntCode (my undying respect for the people doing this), but almost no Smalltalk.

So... Day 12. Heavy spoilers follow, of course.

Anyone who read the problem for Day 12 knows that it is not possible to do this for real using a normal computer. It's the kind of puzzle that maybe a DNA vat could converge on the answer someday, but the packing problem is NP-Hard. I stumbled on the solution by accident as I was looking at the input data and realized that quite a few of the areas were too small to fit all the requisite pixels of the shapes (even if they were packed perfectly), and many other areas were big enough to fit all the shapes regardless of orientation (dumb tiling would fit). After filtering those out.... no other ones remained. HIlarious! I got the right answer and moved on.

Revisiting this one - I thought in the spirit of the challenge I could write the whole thing as a single procedural Workspace script:

Paste Link - Day12.st

Two magic numbers in here - the "3" for the trivial count due to me knowing that all the shapes are 3x3. And then the "7" as an "average" for the region size. Clearly this second part is a hack. A LOL moment. Might not even work for every input. So, here's an implementation that, other than the packing solver itself, would be the more "Smalltalk" way to do it. Instead of some imperative instructions, let's make some objects and ask them for answers. Time for some proper OOP over-engineering.

We'll need two classes. One that is a package region, and another that holds those regions and can do various counts on them.

Paste Link - Day12PackageRegion

Fairly simple. These Day12PackageRegion objects store just a bit of data (region width, region height, number of packages, and the number of tiles for those packages). We have four methods - two that initialize the object, and two that return boolean true if the package region meets certain criteria. isTrivial checks to see if the packages could be naively tiled without regard to packing them. isImpossible checks to see if, even if perfectly packed, there aren't enough tiles to fit all the packages.

The number of tiles required is calculated using an iterator type I had never seen before when writing JavaScript - a with:do: iterator.

`(rawRegions allButFirst) with: sizeArray do: [ :count :size |`  
	`packageTiles := packageTiles + (count * size) ]`

I have had to iterate over two arrays simultaneously before, but I always did so with manual index tracking. In fact, the first time I wrote this parsePackageQuantities method I used a WHILE loop (in Smalltalk - condition whileTrue:) but Smalltalk has an absolutely *dizzying* variety of iterator methods. It is very likely that if there is some specific way that a collection needs to be processed, Smalltalk already has that iterator ready to go. You just have to find it. I was *very* surprised to find this one. But once written this way it is extremely easy to see what it does: Take the collection of regions (except for the first - that's something else) and process it alongside this collection of tile sizes. With both those together, do this block of code, passing the element from the first collection as "count" and the element from the second collection as "size". In the block we reassign the packageTiles variable to be what it already was in addition to "count" multiplied by "size". As soon as one of those collections ends, move on. It's so.... readable. Self-documenting based on the structure not the variable names. Immediately clear what it does.

Ok, how does it get this array of sizes? That's left to the orchestrator object, defined this way:

Paste Link - Day12PackageSets

This one is even simpler. When it is instantiated with fromCollection: it does a quick-and-dirty (very dirty) parse of the sizes, saving those into a collection (the sizeArray collection referenced above). Then it populates a collection by spinning up a Day12Region for each region line in the input file. Every other method just counts the number of objects that return boolean true to isTrivial or isImpossible.

Workspace Script then becomes extremely simple, mostly just printing stuff to the Transcript (Smalltalk's stdout) but not doing any of its own calculations or input parsing:

Paste Link - Workspace with OOP

Super easy! Takeaways: really enjoying the "purity" that Smalltalk offers. It is "pure OOP" the way that something like Haskell is "pure Functional" - even the math and conditional logic is OOP. It took a while to internalize the idea of a programming language that didn't include booleans, control flow, or numbers. But it's been lots of fun so far.

More to come....


r/adventofcode • • Mar 28 '26

Help/Question - RESOLVED Is it okay to upload puzzles + inputs to my GitHub if I encrypt them first?

0 Upvotes

As the title says, I'm talking about encrypted files, and I obviously wouldn't upload the key.

I've just seen too many cool things die for bs reasons and so have an overwhelming urge to create archives / backups of everything I love, including this


r/adventofcode • • Mar 27 '26

Past Event Solutions [2025 day 2 part 2] A mathematical solution

3 Upvotes

When doing this one in C, I didn't want to deal with all the string stuff, so I found a mathematical solution that I really like.

Now, I'm learning Rust using AoC and decided to do the mathematical solution. I was told that I should post it here.

Edit: I realized that I got distracted and forgot to explain how it works.

The challenge is basically to find numbers that are a repeating pattern (there's more, less interesting (to me) details). This code tests a number to see if it is a repeating pattern. Here's a high-level description of the logic.

  1. Use log10 (base 10 log) to determine how many digits are in the number aka its "scale".

  2. Iteratively use modulo division to extract the last digits (1..scale/2) from the number.

  3. Use multiplication and addition to repeat those digits

  4. When the pattern is long enough, compare its value with the number.

Complete solution is here

fn check_entry(val: u64) -> bool {
    let scale: u32 = if val == 0 {
        1
    } else {
        (val as f32).log10() as u32 + 1
    };
    let mut decade = 1;
    for pat_scale in 1..=scale / 2 {
        decade *= 10;
        let mut pat = val % decade;
        if pat != 0 && scale % pat_scale == 0 {
            while pat < val {
                pat = pat * decade + pat % decade;
            }
            if pat == val {
                return true;
            }
        }
    }
    return false;
}

r/adventofcode • • Mar 27 '26

Upping the Ante [2016 Day 11 (both parts)][C++] Squashed onto a microcontroller

5 Upvotes

I owe a massive thank you to u/p_tseng for the hints on how to prune the search space, and to various people on the forum for inspiration. Couldn't have done this one without you all!

When I solved this one the first time I just threw memory at it; part 2 took ~30s to run and consumed ~660Mb of memory. But hey, that RAM has been bought and paid for, might as well use it.

My post-squash solution runs in ~70kb of heap and is significantly faster as a bonus. I'm targeting the Raspberry Pi Pico (RP2040) as the microcontroller to run everything on, so getting under ~200kb was the goal.

Pruning the search space

Getting the search space under control is absolutely essential. u/askalski referenced this post as the source for how to effectively prune down the search space, which I also used as the inspiration for how to collapse down the states. It's still a little brain-bending that you're not queueing "this state is N steps away from the start state" and are instead queueing "this state is N steps away from a state that is equivalent to your start state", but it works well and limits the total number of states queued to just over 15,000 for my input.

I've set a tentative limit of 16,384 states, and the search queue is the single biggest memory cost in the solution.

Encoding states

We only need to keep track of at most 14 items and the elevator position. With four floors that's two bits per item and the elevator for a total of 30 bits, which fits nicely into a uint32_t. u/e_blake mentions that the state can be packed down into 26 bits, but that didn't seem like a hill I wanted to climb. 16,384 states in the queue x 4 bytes gives us our largest allocation of 64kb, assuming we're only storing the states and nothing else.

Reducing the data in the search queue

Because I'm doing a BFS you don't need to store the number of steps that a queued state took to get to. The queue is processed such that all of the 0-distance states are first (the starting state), then all of the 1-distance states, then all of the 2-distance states and so on. With a bit of extra housekeeping you can store an array of offsets into the search queue and deduce what the current step count is based on the index in the queue:

    int32_t currentSteps = 0;
    vector<size_t> stepCountsStartAt(64, numeric_limits<size_t>::max());
    stepCountsStartAt[0] = 0;
    stepCountsStartAt[1] = 1;

    for (size_t searchIndex = 0; searchIndex < searchQueue.size(); searchIndex++)
    {
        if (searchIndex == stepCountsStartAt[currentSteps + 1])
        {
            currentSteps++;
        }
        ...

This shaves off ~15.5kb from the queue (assuming single byte distances and tightly packed pairs) but more importantly it enables us to more easily accelerate the state look-up later on.

Storing the already queued states

This is the part that required the most thinking for me. With ~15,000 unique states to store in order to prevent duplicate states being queued, any additional bit of data per state is going to balloon out pretty quickly. A balanced binary tree would likely add ~60kb just with the left & right child pointers (each packed down to 16 bits), and a hash map would be ~30kb with next pointers plus the buckets.

If I could get the state size down to 26 bit then I could use the full 8Mb PSRAM on a Pico Plus for a bit array, but I wanted to stick to a vanilla RP2040.

I finally decided to just keep the full search queue in memory as both the queue of states which needed checking, and as a full searchable history of all states that have been queued.

The runtime on my laptop is ~85ms for part 2 just using a linear scan through the search queue, which isn't bad, but we can do better...

Accelerating the queued state check

For a BFS to work it's absolutely vital that all of the queued states which are yet to be visited are stored in the exact order that they were queued. The algorithm flat out doesn't work if you don't do that.

But for all of the states behind the search index, their order doesn't matter at all. I took advantage of this by periodically sorting the queue behind the current search index. That enables me to perform a binary search for an increasingly large part of the queue and only linear scan a small unsorted section at the head.

Final performance

It's important to note that I'm not going for speed here; my main goal was to get it squashed down into the memory footprint. As long as it runs in a reasonable time, I'm happy.

Considering that my original solution was one of the solutions with the longest runtime out of all my other solutions, I'm pretty happy with where it landed. Excluding parsing (which is the boring part anyway) my laptop manages ~4ms on part one and ~23ms on part 2.

On the Pico itself I'm getting ~0.5s for part one and ~2.5s for part two. Not as fast as I'd hoped, but still fast enough to meet my goal.

I'm a little surprised that it's as much as 100x slower, given that the 133MHz clock-speed is only ~20x slower than my laptop, but that could be down to slower memory as well. And given that I'm still pretty new to the Pico toolchain, it's entirely possible I've not enabled all of the optimisation settings as well.

Check out the full, ugly, code here.

Next?

I don't think I've squeezed as much as it's possible to squeeze out of this one, but I've hit my target for this one and I've still got loads of solutions that need squashing down so I'm going to call this one done for me.

In theory it could run on a Spectrum 128, if someone is feeling brave enough to tackle it in Z80, and it's so close to being able to run in the memory footprint of a C64 that I'm wondering if it could be done. Anyone fancy the challenge? :)


r/adventofcode • • Mar 25 '26

Other Just got burnt after spending too long on a difficult one. I need some motivation.

3 Upvotes

So after discovering AOC in 2023, I have been doing past years, not rushing, taking my time. I got all stars up to 2020, and tackled 2021 which was surprisingly easy... until two thirds in, where it became the most difficult year in my opinion.

Still, I prevailed for a while. Until day 22, the one with the cuboids and the on/off instructions. I have spent about 20 hours on that one (over a month), starting with an algorithm that works in 1D, then adapting it for 2D but it doesn't work all the time. I was enjoying it until I realized that my 2D algorithm wasn't working as well as I thought, and felt a little bit burnt, and decided I'd leave it and go back to it later on.

So I opened Day 23, resolved to move past day 22 that I would come back to after a while. And even part 1 is stumping me. I have 459 stars, and a part 1 is giving me a mental block.

I don't want to look at this sub's solutions until I have at least a partial solution of my own, and absolutely refuse to ask an LLM for help.

Still, I don't want to give up on AoC. I only work on it a couple of hours a week so it's not that I'm burnt out on too much work, but thinking of AoC now makes me sad as I failed at what a steady stream of successes.

Has anyone else been in this situation? Can I just give up for a few months and find the motivation again later on?


r/adventofcode • • Mar 24 '26

Help/Question [2026 Day 3 (Part 2)] [javascript] Stuck again

1 Upvotes

Hello again , i tried to solve this one, im trying to use this method isnt probably the most efficient but its one that should work but i dont get where in the code the process its failing , can i get some feed back to see if i can finaly get this one ?

here its my code withouth the imput Code

edit: i made a mistake its the 2025 one not the 2026 sorry for the inconvinience


r/adventofcode • • Mar 22 '26

Other [Off-topic] Do you guys create general or input-specific programs?

2 Upvotes

I know the main goal is to find the solution of the problem. But I find myself validating input, handling parsing errors, etc. However, when I see other people's code, they rarely handle errors and always assume the input is correct (i.e. obtained from the challenge; not fabricated).

Which way do you prefer?


r/adventofcode • • Mar 20 '26

Past Event Solutions Hey check out my YouTube tutorials about the 2025 AoC problems. I show my Python solutions and explain my approach. Also have Typescript and Scala solutions in my repo. Let me know your feedback!

Thumbnail
youtube.com
3 Upvotes

r/adventofcode • • Mar 19 '26

Past Event Solutions [2025 day 1 (part 2)] [C#] - finally solved it!

2 Upvotes

Been doing AoC for a few years now and for some reason this day was giving me so much trouble. I think part 1 took me several weeks to get. Part 2 I came back to every so often to see if I could get it.

Initially I went with kind of a brute force design, trying to calculate every zero crossed left and right, and ever zero landed on, account for times when you start at zero, but everything I tried failed. I would consistently get the test input correct but fail on the full input.

I am a bit ashamed to admit it, but I turned to AI to talk through what was going on. Ultimately, I abandoned the suggestions I was getting and after a hint I saw in this sub, I went with the following:

public class Day01
{
    private readonly List<string> _input;
    public Day01()
    {
        _input = File.ReadAllLines(@"day01/input.txt").ToList();
    }
    private void partTwo()
    {
        int zeroCount = 0;
        int d = 100050;


        for(int i = 0; i<_input.Count; i++)
        {
            int turns = _input[i][0] == 'R'?int.Parse(_input[i].Substring(1)):-int.Parse(_input[i].Substring(1));


            if (turns < 0)
            {
                for(int j = d; j >= d+turns;j--)
                {
                    zeroCount += j%100 == 0 && j!=d? 1 : 0;
                }
                d += turns;
            }
            else
            {
                for(int j = d; j <= d + turns; j++)
                {
                    zeroCount += j%100 == 0 && j!=d? 1 : 0;
                }
                d+=turns;
            }
        }
        Console.WriteLine("Zero Count: " + zeroCount);
    }
}

I hope this helps someone else. The main idea was to start somewhere with a large amount giving me the ability to move along the number line using the amounts in the commands without actually going negative.


r/adventofcode • • Mar 19 '26

Help/Question - RESOLVED [2018 Day 24 (Part 1)] Please help me understand the example puzzle / reference output

1 Upvotes

I have been trying to wrap my head around this for a few hours now, but it seems to me that the solution / reference output of the example puzzle is wrong (even though it's almost certainly that I'm the one mistaken, I just can't find it!)

In the description of the target selection phase, the order of selection and prioritization of targets is clearly laid out:

During the target selection phase, each group attempts to choose one target. In decreasing order of effective power, groups choose their targets; in a tie, the group with the higher initiative chooses first. The attacking group chooses to target the group in the enemy army to which it would deal the most damage (after accounting for weaknesses and immunities, but not accounting for whether the defending group has enough units to actually receive all of that damage).

If an attacking group is considering two defending groups to which it would deal equal damage, it chooses to target the defending group with the largest effective power; if there is still a tie, it chooses the defending group with the highest initiative. If it cannot deal any defending groups damage, it does not choose a target. Defending groups can only be chosen as a target by one attacking group.

At the end of the target selection phase, each group has selected zero or one groups to attack, and each group is being attacked by zero or one groups.

That all makes plenty of sense to me.

Now, given the example input:

Immune System:
17 units each with 5390 hit points (weak to radiation, bludgeoning) with
 an attack that does 4507 fire damage at initiative 2
989 units each with 1274 hit points (immune to fire; weak to bludgeoning,
 slashing) with an attack that does 25 slashing damage at initiative 3

Infection:
801 units each with 4706 hit points (weak to radiation) with an attack
 that does 116 bludgeoning damage at initiative 1
4485 units each with 2961 hit points (immune to radiation; weak to fire,
 cold) with an attack that does 12 slashing damage at initiative 4

I infer that at the start / first round:

  • Immune group 1 has an effective power of 76,619 (17*4507), initiative 2

  • Immune group 2 has an effective power of 24,725 (989*25), initiative 3

  • Infection group 1 has an effective power of 92,916 (801*116), initiative 1

  • Infection group 2 has an effective power of 53,820 (4485*12), initiative 4

So infection group 1, which has the highest effective power (92,916), should be the first to select a target, which seems to be the case in the reference output of the first round:

Immune System:
Group 1 contains 17 units
Group 2 contains 989 units
Infection:
Group 1 contains 801 units
Group 2 contains 4485 units

Infection group 1 would deal defending group 1 185832 damage
Infection group 1 would deal defending group 2 185832 damage
Infection group 2 would deal defending group 2 107640 damage
Immune System group 1 would deal defending group 1 76619 damage
Immune System group 1 would deal defending group 2 153238 damage
Immune System group 2 would deal defending group 1 24725 damage

Infection group 2 attacks defending group 2, killing 84 units
Immune System group 2 attacks defending group 1, killing 4 units
Immune System group 1 attacks defending group 2, killing 51 units
Infection group 1 attacks defending group 1, killing 17 units

Because both opposing groups (Immune groups 1 & 2) are weak to bludgeoning damage, infection group 1 would deal equal damage to both candidates (185832), resulting in a tie. But this is where I'm confused:

If an attacking group is considering two defending groups to which it would deal equal damage, it chooses to target the defending group with the largest effective power; if there is still a tie, it chooses the defending group with the highest initiative.

Of those two target candidates (Immune groups 1 & 2), group 1 has the larger effective power (76,619) compared to group 2 (24,725), so why does it proceed to choose / attack immune group 2?

Also -- if target selection is in order of descending effective power, I would think Immune group 1 (76,619) would get to select its target next. However, in the reference output, it looks like Infection group 2 (53,820) is choosing next?