r/adventofcode • • 19h ago

Meme/Funny Reading [2026 Day 4 Part 2] in despair, until...

Post image

I somehow guessed exactly what part 2 would be while solving part 1, and thus avoided the naive O(6^n) solution for it, instead dealing every letter from a barcode into buckets like playing cards and checking all of them for homogeneity. Code finished in 2 seconds :)

92 Upvotes

50 comments sorted by

55

u/benjymous 19h ago

Yeah, my part 2 was adding input.Replace("\n", "")

6

u/According_Bowler9565 15h ago

I can't tell if i feel smug or cheated!

1

u/atrocia6 11h ago

My part 2 was basically replacing:

cost = 0
for line in open(0):

with:

barcode = ''.join(open(0).read().split())

16

u/RazarTuk 19h ago

I think my solution is technically O(n2), although if you're naïvely going off number of nested loops, you'd mistake it for O(n3)

I just go: For each code length, from each position in the first repeat, step forward size characters at a time. Then at each step, I check if it's either a ? or matches the color I'm looking for, updating it if I'm looking for ? and find an actual color

2

u/not-the-the 19h ago

Well that seems to be pretty much the exact logic I did but in a different wrapping.

I instead just ignored every ? and checked every pile of "characters in position n modulo [currently checked cycle]" for only containing one letter.

Thankfully, [].every(_=>false) outputs true. :)

2

u/RazarTuk 19h ago

Yeah, that innermost part of my code was just:

var cmp = line[start]
var idx = start + size
while (idx < line.length) {
    if (line[idx] == '?' || line[idx] == cmp) {
        idx += size
    } else if (cmp == '?') {
        cmp = line[idx]
        idx += size
    } else {
        continue@size
    }
}

6

u/MrBoblo 18h ago

Mine is the same in principle, but a bit slower since i save every nth step to a list, then make a set of the list, discard "?" And check if the set is 0 or 1 long :p

2

u/Overall_Purchase_279 17h ago

Samee, although I was thinking that there should definitely be another optimization possible, turns out it's FFT... Yea no I couldn't have possibly done that lol

1

u/jmgimeno 16h ago

I do more of less the same, but I create an array that for each possible residue module step size stores the first letter found. When for a letter at a given position when dound module residue size you find another letter, you discard the step size.

1

u/TheZigerionScammer 2h ago

I think my solution is technically O(n2), although if you're naïvely going off number of nested loops, you'd mistake it for O(n3)

Is your outermost for loop just iterating over every line in the input? Mine does that and I wouldn't count that since each line is independent of each other, unless I guess you chose to memoize the solution. It's basically just running the same program 400 times.

2

u/Roppano 16h ago edited 16h ago

reading the comments, I think I have more unique solution:

my idea is based on congruence. if an instruction has length of i, then it only works for the barcode if at any position % i there's only one kind of character (or ?, ofc).

01234567
01201201 <-- mod 3
01230123 <-- mod 4
??bg?v??

you'll need at least as many instructions as there are distinct colors in the barcode, so I check that first. I put all the determined characters in buckets based on position % i, and see if I get any clashes. b and g go into buckets 2 and 0, and v would also like to go in bucket 2, but that's already occupied by b.

So next, trying i = 4, now the bucket looks like

0123
?vbg

so that's a correct, and minimal solution. Written in rust, part2 runs in 14ms

1

u/not-the-the 15h ago

my exact algorithm

2

u/MattieShoes 13h ago

Fundamentally same exact solution. You can make new strings for each bucket and scan them to see if each has more than one color, or use a set or hash for each bucket, whatever.

1

u/abraxasknister 14h ago

hello, fellow rustecean. I think this is quite similar, but instead of calculating %i of the iteration variable, I use (0..i).cycle().zip(promt.chars()).

1

u/ColeCube 12h ago

That's exactly what I did

9

u/AlpacaDC 17h ago

I was absolutely dreading part 2 since it took a lot of time and brain power to solve part 1. Luckily I just had to change the input parsing.

1

u/Arctos_FI 13h ago

Yeah same. 3.5h for part 1, 5min for part 2

14

u/Positive_Concert_774 19h ago

I'm truly puzzled what the heck would lead anyone to make an O(6^n) solution for this

25

u/Daniel_Rybe 19h ago

I'm guessing that the most brute-force approach would be to iterate over all possible patterns starting from length 1 and stop when one fits the input. That might be O(6^n).

45

u/vegan_antitheist 18h ago

Yeah, what kind of idiot would do that?

You want to see my git history? Sorry, my dog ate it.

9

u/andrewsredditstuff 16h ago

How do you do, fellow non-idiot. I too definitely did not do that.

4

u/janiczek 13h ago

For a whole hour I definitely did not do that.

2

u/MattieShoes 14h ago

I didn't commit until after I solved part 2, then replaced my part 1 solution :-)

caching results made that perfectly viable for part 1.

1

u/headedbranch225 16h ago

I may have thought of that, and did come to the realisation you can iterate from alphabet length up, since it must include at least all the colours in the original barcode, which is a slight optimisation at least, but then I got stuck trying to generate a list of all the possible instruction sequences

3

u/velkolv 19h ago

Hot Springs flashbacks and plan to slap memoization on top of it for Part 2.

2

u/Demiu 18h ago

Well... there are two. One where n is the length of the checked pattern (you check every possible combibation of length n). The other where n is the number of ?s. The 2nd one is a little more reasonable

3

u/Ok_Manufacturer_8213 16h ago

I feel soo dumb for not understanding it

3

u/QultrosSanhattan 14h ago
  • Solved part 1 in n^2
  • Eric at part 2: C-C-C-C-COMBO BREAKER!

1

u/stupid__mistake 9h ago

My part 1 solution is O(n2), but that's assuming worst case input. Unless you have pathological input you won't approach the asymptotic worst case because one of those O(n) loops will always terminate very quickly on a mismatch.

I simply concatenated my input and called the part 1 function again for part 2 and the whole thing runs in ~10ms - it takes five times as long to print the result to the console.

TL;DR don't optimise away from a quadratic solution when n is very small.

3

u/Danefantom 10h ago

Solution run time for part 1 ~ 60s.
Looking at part 2, "Uh oh.... Ah, I'm dumb" ~ 0.016s

5

u/_alba4k 18h ago

My solution is technically O(1) since the input is constant.

It takes around 1.34e3106 years to run, but that's no big deal right?

(I trie the naive appraoch first as the input was reasonably small and it ran part1 in ~10s. tried part2 for the lolz and it got OOM killed after a few minutes)

-2

u/PatolomaioFalagi 18h ago

My solution is technically O(1) since the input is constant.

That's not how this works. That's not how any of this works.

Next you tell us that no computer is Turing-complete, because they all have finite memory.

5

u/_alba4k 18h ago

First, that was a joke. secondly, that's exactly how it works. A deterministic function with no input that terminates is per definition O(1) as the runtime is a constant.

Secondly, the claim "a computer with finite memory is not turning complete" is also perfectly correct from a theoretical point of view.

-4

u/PatolomaioFalagi 17h ago

First, that was a joke.

I know you intended that as a joke.

secondly, that's exactly how it works. A deterministic function with no input that terminates is per definition O(1) as the runtime is a constant.

The function does have input. It's string matching (roygbv\?)*. What are you talking about?

Secondly,

That's your second "secondly".

the claim "a computer with finite memory is not turning complete" is also perfectly correct from a theoretical point of view.

Yes, I was continuing your joke.

3

u/_alba4k 17h ago

The function does have input.

depends on what you define the problem to be. for the sake of claiming the constant-time I was considering "output the correct number for this specific AOC input" to be the problem to solve. a program that just print "12345" would solve that if that was the correct answer

That's your second "secondly"

secondly, you're perfectly right

I know, I was continuing your joke

secondly, oops 😅 my bad

1

u/UnimportantMessages 16h ago

2s? My C# solution finished part 2 in 1ms runtime. Not sure you’ve landed on the right algorithm there buddy.

2

u/not-the-the 16h ago

yes i am sure i didnt. javascript btw

and to be fair im not on high-end hardware so anything <10s is fine by me

2

u/vegan_antitheist 18h ago

I brute forced the first part. It was easier starting from scratch than fixing what I had. I won't drop the first commit even though it's embarrassing if anyone ever sees it.
My solution now doesn't even use recursion. It's so simple.

3

u/RazarTuk 18h ago

... what were you doing at first that you needed recursion?

3

u/vegan_antitheist 17h ago

I generated all possible instructions. It's easy to write the code. You can still use recursion by calling the same method with the same barcode and the next chunk size.

int solve(char[] barcode, int n) {
  ...
     return solve(barcode, n + 1);
  ...
}

The first part was still solved in almost no time. But the second one would have taken hours, days, maybe years. I can't tell.
It's about 10 years since I was a student and did such challenges. How I only write code for banks and other companies. They also often don't remember the exact licensing agreements, but they don't really need to optimise code as long as the can throw hardware at it.

3

u/MattieShoes 14h ago

Every ? produces a tree with six leaves, where it's replaced with one of the colors. For multiple ?, recursion. Track and return the leaf value with the least cost.

The code is very simple and works fine for part 1, and can probably be optimized by stuff like not introducing new colors. But obviously with >10,000 ? in part 2, not viable.

1

u/Sharparam 15h ago

There's nothing that would ever need recursion because everything you write as recursion could be rewritten to not be recursive.

My Ruby solution uses recursion and runs in ~520 ms (edit: ~480 ms after small optimization) for both parts on my work macbook: https://tangled.org/sharparam.com/advent-of-code/blob/main/src/y2026/d04/solve.rb

Could I rewrite it to not use recursion? Probably, but sometimes it's easier for me to think with recursion.

1

u/rigterw 14h ago

Recursively fill in every letter option

1

u/wjholden 17h ago

Thanks so much for this - your analogy of playing cards helped me understand a fast algorithm to solve this puzzle!

1

u/PercussiveRussel 16h ago

I was being too clever for my own good and parsed the number as 6 bitmasks of known digits. Part 1 runs in 150 us with u16s. After pulling in BigInt crate, my part 2 runs in 6 ms :(

1

u/ConfectionUsed2828 13h ago

Code finished in 2 seconds :)

Are you me..?

1

u/XNeedNoName 12h ago edited 10h ago

i used bfs to solve part 1 (sadly cant check a graph with 3.5401 * 10^10385 nodes)

(edit: im so dumb i solved part with a solution i thought of and rejected within the first 2 mins of trying to solve part 1

1

u/atrocia6 11h ago

For me this was one of those days where the solution I used for part 1 was adaptable to part 2 with minimal modification; my Python solution for part 2 runs in a bit under .2s.