r/adventofcode • u/daggerdragon • 2d ago
SOLUTION MEGATHREAD -❄️- 2026 Day 4 Solutions -❄️-
OUR USUAL ADMONITIONS
- You can find all of our customs, FAQs, axioms, and so forth in our community wiki.
AoC Community Fun 2026: Th* Adv*nt Gam*s
- 13 DAYS until submissions cutoff in submissions ultrapost on this 17th of Month 12 at 18:00 UTC-5!
Today's Bouts: World Snow Avoidball Championships
"If you can dodg* a wr*nch, you can dodg* a [snow]ball."
— Coach Patch*s O'Houlihan, Dodg*ball: A Tru* Und*rdog Story (2004)
Today's programming possibly consists of:
- Pool Play (Group Divisions)
- Pick a glyph and do not put it in your program.
- Avoiding fifthglyphs is traditional.
- Match Formats (Foam, Cloth)
- Shrink your solution's fifthglyph count to null.
- Your script might supplant all Arabic symbols of 5 with Roman glyphs of "V" or mutatis mutandis.
- Thou shalt not apply functions nor annotations that solicit said taboo glyph.
- Knockout and Trophy Rounds
- Thou shalt ambitiously accomplish avoiding AutoMod’s antagonism about ultrapost's mandatory programming variant tag >_>
Stipulation from your mods: As you affix a submission along with your solution, do tag it with [Adv*nt Gam*s] so folks can find it without difficulty!
--- Day 4: Perilous Pier ---
Post your script solution in this ultrapost.
- First, grok our full posting axioms in our community wiki.
- Affirm which jargon via which your solution talks to a CPU
- Format programs using four-taps-of-that-long-button Markdown syntax!
- Quick link to Topaz's Markdown (ab)using provisional script host should you want it for long program blocks
24
Upvotes
•
u/topaz2078 (AoC creator) 2d ago
[JARGON: look it works this way]
Sorry for our lack of warning; dragon mod forgot to say that automod also supports [JARGON: ...] or [SYNTAX: ...] if your goal is to avoid fifthglyphs.
5
u/AllanTaylor314 2d ago edited 2d ago
[JARGON: Python] 00:06:41/00:08:00
script
[SYNTAX: Uiua]
script with annotations or pad sans fifthglyph
Kinda slow at 4s on actual input. Python only took 79 ms.
[Adv*nt Gam*s]
Avoid fifthglyphs? Avoid most standard glyphs with Uiua
3
u/Busy-Contact-5133 2d ago edited 1d ago
[LANGUAGE: Golang]
part2 was a joke. I'm dreadful how hard the tomorrow's part 2 would be after this.
https://github.com/dawit909/aoc/blob/main/d04/main.go
3
u/soolpro 1d ago edited 1d ago
[LANGUAGE: Python]
The variable names are in Finnish, but here we go.
The splitting function was a bit tedious for me to write and in retrospect I realize that the last modulo length section wouldn't have had to be inflated to the same lenght as the other pieces, but that was what my brain was wrapped around when I came up with the solution. I was happily surprised to see that by my standards the code ran quite fast.
Part 1
Part 2.
3
u/JWinslow23 1d ago edited 1d ago
[JARGON: Python] [Adv*nt Gam*s]
I don't usually aim for such bonus goals as today's, but I thought it did look fun to try. Can I avoid all fifthglyphs in a full Python script solution? It's difficult without a doubt, as so many words important to Python syntax, builtins, and many a standard library contain that unsought glyph (
d*f,l*n,rang*,n*xt,it*rtools, and so on). But trust my word or not, I found a not-half-bad way of adapting my non-lipogrammatic solution approach to accomplish this goal. It works thusly:My first task is to supplant two particular functions with much utility, but which also contain fifthglyphs:
l*nandrang*(which I callcountandspanaccordingly). My only way of constructing a function is usinglambda, as Python's usual word for this has a fifthglyph.countadopts a common idiom to obtain counts of things in a box: summing a1for all things in it.span, as it is a lambda function, must turn to using "walrus" symbols (:=) for assigning to things such asnfrom within a computation. And to don-initialization and list-building both in a row, I put that first part in a solo "pair" (which is truthy), following it with a logicaland(which short-circuits) to finally output that list that was built.Both main actions my solution approach will do also sit in custom functions.
amount_is_validwill confirm if an amount of instructionsnis a valid way of dividing a colorstrip into chunks. It looks at all first colors of chunks as a group, moving on to all following groups of colors within chunks, and it confirms if all groups contain up to a singular distinct color (minus unknown colors, naturally).{...}). What Python calls this symbol pair in this situation - what do you know - also has a fifthglyph, which is why I go with this syntax.first_valid_amountwill go up in amount, amass all amounts that could possibly work, and output its first amount found. (It's annoying that I can't do this withn*xt, so this script must wait for all such amounts...but ho-hum, that's just how it is.)sys.stdin, as again, Python's usual word for taking .txt input has a fifthglyph. Upon doing astripto all colorstrips (ain't that funny?), I'm almost through; I mapfirst_valid_amountto all colorstrips and sum all amounts up for Part 1, and I join all colorstrips into a singular colorstrip and callfirst_valid_amounton that for Part 2.I'm happy that I did accomplish today's bonus goal...although by this point, Wastl got around to publishing his fifth prompt. (How many hours is too many to work on such a bonus goal? 😵💫)
CHANGING OF MY WORDS: Talk about why I can't call
s*t2
u/_throwaway237849 2d ago edited 1d ago
[LANGUAGE: Rust]
solution
My puzzle input had each line as a maximum of 8 characters long which let me optimize part one to do essentially SWAR on a
u64.For part 2 I did the same as part one just using
std::simd.2
u/WilkoTom 2d ago edited 2d ago
[SYNTAX: Python] [Adv*nt Gam*s]
Solution with no filthy fifthglyphs
This is no doubt awful and slow. But it lacks that particular glyph that I shall not discuss.
2
u/Jakub_koo 2d ago edited 2d ago
[LANGUAGE: Python]
Here's my day 4 part 1/2 solution:
2
u/bigtlb 2d ago edited 1d ago
[LANGUAGE: Free Pascal]
https://github.com/bigtlb/advent-of-code-2026-in-object-pascal/blob/main/src/days/day04.pas
2
u/blu3teeth 2d ago edited 1d ago
[LANGUAGE: Python]
Took a while to understand the question, but I think my solution is quite intuitive - kinda how I would do it by hand.
Think about something like
rgbrgbrgbrwhere the answer is 3. If you split this into substrings of length 3 (padding?at the end) and read down the columns, it looks like this:So I'm looking for each potential length
N, where the different characters when reading the lines are either:?2026/aoc4.py
2
u/e_blake 2d ago
[JARGON: mfour] [Adv*nt Gam*s]
m$(printf f|tr a-f /-:) -Dinput=dayfour.input dayfour.mfour
Drags out my solution to a lousy forty-four wall clock ticks. But no digits or forbidden fifthglyphs, and just two cyclic macros form my post-bootstrapping algorithm guts!
On an input of ??bg?v??, tracing this shows:
2
u/MrRbahi 1d ago edited 1d ago
[LANGUAGE: Python]
[Solution]
I ironically solved today on a train, so it took way longer than it should have to model the different loops and conditions in my head.
I'm sure there are easier ways to do it, but what I did was start with the smallest number i+1 of instructions code[:i+1] and check if each of them repeats in the code at the interval of i+1. I also replaced question marks with the first encountered color in my checks.
15
u/4HbQ 2d ago edited 2d ago
[LANGUAGE: Python]
This comment explains what f() is doing.
An alternative version of f() using regex:
10
u/JWinslow23 2d ago
[LANGUAGE: Python]
Solution writeup
Code (GitHub)
A surprisingly simple puzzle (after I looked at it from a different perspective - not as rows but as columns, if that makes sense). In fact, here's the entirety of the solution I published:
8
u/Smylers 2d ago edited 2d ago
[JARGON: Vim button pushing] Load your input into Vim and push buttons as in this list:
Your part 1 solution should show up. Initially try all at 1 colour. For all rows with no clashing colours, stay at 1 and discard that row's colours. Rows still with colours go up to 2. Put additional dots in thing to match, and go again. Go round till no colours. Add up with
@vfrom Day 2.[Adv*nt Gam*s] Not using fifthglyph by avoiding particular buttons, and with additonal pushing of
Ctrl.6
u/michelkraemer 2d ago edited 2d ago
[LANGUAGE: Rust]
Solution
Using the same
decryptfunction for both parts. The function tries successively longer lists of instructions until it finds one that matches. It produces each list of instructions by taking the firstlcharacters (where1 <= l <= input.len()) and then matching it with the input at positionsl,l*2,l*3,etc. Whenever the list of instructions contains a?character and the input contains a real character at the corresponding position, the function replaces the question mark with the real character. This way, it successively fills in the blanks in the list of instructions. If it gets to the end of the input without finding any non-matching characters, the function has found the fewest number of instructions.The whole program runs in
314µs.EDIT: Saved an allocation. The whole program now runs in 109µs.
5
u/Ok-Bus4754 2d ago edited 2d ago
[Language: Python]
brute force using sets to compare to optimize
https://github.com/Fadi88/AoC/blob/master/2026/days/day04/solution.py
start by a length of 1 (smallest possible , one color repeating for good) and keep going trying all size up
p1: 3 ms p2: 1.5 ms
will port later to rust , and share compartive benchmarks , maybe even think of an optimzed solution
5
u/semi_225599 2d ago
[LANGUAGE: Rust]
Map each character to a separate bit,
?is all of the bits as a wildcard. Then fold chunks across the barcode with bitwise-ands. If any value becomes 0, you have a mismatch and can try the next largest chunk. If not, you've found the smallest possible chunk instruction.5
u/pred 2d ago
[Language: Python] GitHub/Codeberg
5
u/xoronth 2d ago edited 2d ago
[LANGUAGE: D]
paste
Interesting language for the day, I actually kinda like it. It's like C but with way more ergonomic? But not C++-like. Glad to have tried it.
For fun, a version without fifthglyph. This was tricky!
5
u/extractedtarball 2d ago
[LANGUAGE: c]
206 bytes, reads the input from stdin, takes ~1.4ms on my zen4 laptop. Most of the complexity is squeezing part 1 into the part2 solution.
5
u/tranjeroex 2d ago
[LANGUAGE: Roc]
Same solution for both parts. Iterate from 1 to the length of the barcode, set an initial list of wildcard '?' and compare+set colors until the first length where we don't get any conflicting color.
Github
5
u/light_ln2 2d ago edited 2d ago
[LANGUAGE: python]
Initially solved like everyone else, but finally got some time to make a solution using Fast Fourier Transform that guarantees n*log(n) time complexity. Additional fun was to use numpy to minimize number of lines and the length of the longest line!
4
u/mynt 2d ago
[Language: Python]
The general idea is to try every length from 1 up to the length of the barcode. Create a blank barcode of your chosen length and then overlay the blank barcode with the given barcode, fill in any letters from the given barcode to your blank then move the blank(previously) barcode along and repeat, if we ever try to write a letter onto our blank that is different to one already there then increase the size of the blank and try again. Same approach works for parts 1 and 2 just feed in the input as appropriate.
4
u/lunar_mycroft 2d ago edited 2d ago
[LANGUAGE: rust]
Part 1 took longer than I'd like, but thankfully was sufficient to solve part 2 easily enough.
Full code. For part 1 I check for the special case of a fully illegible barcode (and early return 1), otherwise I check every possible program length to see if it would work. I start by simply copying the first
lencharacters as the program, then loop through the remain letter checking if they're consistent, and replacing'?'s in the program with a concrete letter when I encounter that case. The only real optimization is that I reuse the same program buffer for the entire line, which in theory cuts down on allocations. Part 2 just concatenates all the lines and reuses theshortest_programfunction from part 1. Parsing takes 80.44µs, part 1 takes 235.1µs, and part 2 takes 903.8µs.Refactored
shortest_programintolib.rssince it was shared. Also changed it to take a mutable reference to the program buffer instead of allocating one itself. This speeds part 1 up to 116.3 µs on my machine (which is a bit surprising to me, I would have thought the default allocator would be decent at cheaply reusing the same memory for each new vector.Checking that the input is ASCII doesn't appear to meaningfully slow down parsing, but allows me to iterate over the individual bytes instead of
chars, which is much faster. This speeds up part 1 slightly to 107.6µs and part 2 significantly (to 117.6µs)./u/maneatingape strikes again. Eliminated the program buffer all together by using
Iterator::step_byto check that each byte in the potential matches with the barcode. (Note: the second line of the inner closure is a manual implementation ofitertools::Itertools::all_equalbut that turned out to be slightly slower). This speeds up part 1 to 78.36µs and part 2 to 72.35µs4
u/johnpeters42 2d ago
[Language: Python]
Part 1
For each line, check possible substring lengths from 1 to len(line):
For each character in the line (C1), compare it to the relevant character of the substring (C2).
Part 2 just concatenates the lines of the input file and runs that through the same function.
4
u/encse 2d ago
[LANGUAGE: C#]
https://aoc.csokavar.hu/2026/4/
4
u/mendelmunkis 2d ago
[LANGUAGE: C]
If only this, AoC has taught that it it smart to look at both axis of a combinatorial calculation
Additional link for DDOS
185 μs/267 μs
4
u/lboshuizen 2d ago
[Language: F#]
github.com/lboshuizen/aoc26
The fewest instructions is the shortest period p: every residue class mod p may hold at most one known colour. Part 2 joins the lines and asks the same question.
4
u/janiczek 2d ago
[LANGUAGE: BQN]
Not fast enough for part 2 but I felt like a wizard, so...
4
u/xiety666 2d ago edited 2d ago
[LANGUAGE: C#]
https://github.com/xiety/AdventOfCode/blob/main/2026/0/Problem04/Problem04.cs
4
u/Ok-Bus4754 2d ago
[Language: Rust+Python]
port of my earlier brute force soultion
https://github.com/Fadi88/AoC/blob/master/2026/days/day04/src/lib.rs
https://github.com/Fadi88/AoC/blob/master/2026/days/day04/solution.py
4
u/azzal07 2d ago
[LANGUAGE: awk]
4
u/EverybodyLovesChaka 2d ago
[LANGUAGE: MS Excel 2003]
Part 2:
I wrote this formula to print the first 20 nth letters of the input, offset by x:
=MID($A$1,$F$3+(A29*0),1)&MID($A$1,$F$3+(A29*1),1)&MID($A$1,$F$3+(A29*2),1)&MID($A$1,$F$3+(A29*3),1)&MID($A$1,$F$3+(A29*4),1)&MID($A$1,$F$3+(A29*5),1)&MID($A$1,$F$3+(A29*6),1)&MID($A$1,$F$3+(A29*7),1)&MID($A$1,$F$3+(A29*8),1)&MID($A$1,$F$3+(A29*9),1)&MID($A$1,$F$3+(A29*10),1)&MID($A$1,$F$3+(A29*11),1)&MID($A$1,$F$3+(A29*12),1)&MID($A$1,$F$3+(A29*13),1)&MID($A$1,$F$3+(A29*14),1)&MID($A$1,$F$3+(A29*15),1)&MID($A$1,$F$3+(A29*16),1)&MID($A$1,$F$3+(A29*17),1)&MID($A$1,$F$3+(A29*18),1)&MID($A$1,$F$3+(A29*19),1)&MID($A$1,$F$3+(A29*20),1)
Input is at A1, offset is at F3, different values of n are in column A.
With offset 1, I looked for values of n where there was only one letter apart from question mark (pasted the output into Notepad++ and did a regex search).
This yielded 29 possibilities in the first 2000 values of n. I got rid of all the other values of n and increased the offset by 1. Eyeballing the output revealed only one remaining possibility, which turned out to be the answer.
4
u/DuoSRX 2d ago
[LANGUAGE: Uiua]
Pad link
4
u/snailcuber 2d ago edited 1d ago
[LANGUAGE: ruby]
code golfed down to 79 characters
could get it down to 78 but it was too slow my for taste (79 takes ~1s on input, 78 takes ~70s on input)
EDIT: found a 78 variant that is even faster @ ~0.75s
and a 79 variant that is much faster @ ~0.3s
4
u/mvorber 2d ago
[Language: F#]
https://github.com/vorber/AOC2026/blob/main/day4.fs
Was quite surprised (pleasantly) when part2 turned out to use exactly the same solution as part1 with just a tiny change from Seq.sumBy to Seq.concat :)
4
u/kiptronics 2d ago
[Language: Python]
I rarely share my solutions here because I'm really dumb but was really pleased with this solution so I wanted to share. I guessed that for a valid sequence length n that the set of every nth character would be either a question mark or the same character, and that guess happened to be correct it seems. Also tried to save time by starting with the amount of unique characters as my guess for the length of the sequence. Happily accepting any feedback on my solution!
4
u/siener 1d ago edited 1d ago
[LANGUAGE: Dyalog APL]
Update: Shorter version as promised. I'm sure it can be made shorter still, but I think this is good enough
Original solution: Like yesterday, I might post a less verbose version later
4
u/musifter 1d ago edited 1d ago
[LANGUAGE: dc]
This one was fun to do in dc. First step is converting the input to numbers, and I chose the digits 0-6 with 0 being the wildcard (bringing in the question of what about leading 0s?). I also needed to decide if the strings needed to be reversed (with
rev) or handled backwards somehow.And the answer to both these questions is "no, it's not a problem". Reversed barcode strings (or solving in reverse) gives the same answer. This is because the matching pattern mask puts the same values in the same equivalence classes, even if the names are changed. For example, consider a string of length 8 with a pattern of length 3:
As you can see, going in the other direction swaps the names/residue of 0 and 1 (and 2 remains the same). This is not a problem, as the name doesn't matter, only that the things get divided into the same sets.
As for leading 0s, since we're going backwards those are just wildcards that can't ever fail. And by the above, we can see that wildcards at the start as well can be ignored (that just shifts the names... so long as the internal wildcards are there to space things out, the ones on either end don't matter). And so, if you want to simplify things, you could strip out leading and trailing 0s. This isn't really so important though (for part 2 I have only two 0s on one end and five on the other). But with dc, I'm getting the 0s removed from the tail end for free (as I'm iterating through the barcode with divmod
A~, so I start from the right/low digits).I'm also really happy with how the processing of the pattern mask goes:
That's it. The stack coming in here has
pattern[i%len] barcode[i] barcode[i]on top. The first line calls theCmacro to copy the barcode into the pattern, and replaces the value on the stack with the new one. This is done with simply+dd li:p... as p[i%len] is 0 to get here, the + deletes it, then we duplicate the barcode[i] twice (once to change the value in the array, the second to replace p[i%len] on the stack).With the pattern appropriately adjusted,
-*is our arithmetic logic to get the bool we need (in negative logic where 0=true, other=false). The-does comparison, and the*does an OR. With that, we test if the result is false and run a quit macro that adjusts the stack as needed for exiting the loop early,r3R1+. That's a little stack manipulation that ends with the rest of the barcode digits on top... we then add 1 to that to make sure it's non-zero, as that becomes out bool for success (as the loop that processes the barcode ends when the barcode is 0 at the bottom of the loop... which falls through).Sorry if that a bit long, I thought it was cool.
Part 1:
For part 2, we can just use
trto strip the newlines first and feed it into the same code. Although, since there's only one line, we can also strip out the outer loop code and get things shorter:This is going to be a bit slow... but thanks to the new GNU dc using hash tables for the arrays, it won't be ludicrously so for other people (the hash tables slightly out perform my dc using skiplists for this problem).
Source: https://pastebin.com/7KqFPMS6
4
u/ExploitSage 1d ago
[LANGUAGE: Python]
GitHub
TIL Python Loops can have an
elseclause!4
u/hugseverycat 18h ago
[LANGUAGE: Python]
https://github.com/hugseverycat/aoc2026/blob/master/day04.py
Hopefully nice and readable, with comments. Basically I tested longer and longer ? instructions (e.g. if I'm testing for a 5-character instruction, I start with ?????) and replace ? with actual colors only when they become necessary.
1
u/Scared_little_boi 2d ago
[LANGUAGE: cpp]
1
u/morfanaion 2d ago edited 27m ago
[LANGUAGE: C#]
Part 1: https://github.com/morfanaion/AoC/tree/feature/2026/2026/Day04/AoC.2026.04.1
Part 2: https://github.com/morfanaion/AoC/tree/feature/2026/2026/Day04/AoC.2026.04.2
1
u/fridi_s 2d ago edited 1d ago
[LANGUAGE: Fuzion]
GitHub
The trick in part 2 was to use exceptions to stop early and avoid O(n³) performance. In Fuzion, exceptions are a kind of an effect that uses `abort` with a result.
One possible addition to the Fuzion API:
Sequence.first_match, a combination offilterandfirst, helps to save one line of code.1
u/Sea_Cut_6635 2d ago edited 2d ago
[language: Python]
Might not be the speediest but I've tried to explain what's happening clearly.
def find_patttern_length(barcode):
'''
Step 1. If it's blank then 0
Step 2. If it's entirely one letter or '?' then length = 1
Step 3. Check every n letters to see if they match. e.g every 2nd letter [r,b,r,b] has 0,2 as r and 1,3 as b. Repeated for 3,4,5 until you get each set just one letter or '?'.
input: barcode is a list of letters e.g [r,b,?,r,b]
'''
print(f"Barcode: {barcode}.")
# If there is only one value
if len(set(barcode)) == 1:
return 1
elif len(set(barcode)) == 0:
return 0
for n_steps in range(1, len(barcode) + 1):
step_items = dict()
for i in range(n_steps):
step_items[i] = set()
# Split the barcode items into groups
for i in range(len(barcode)):
step = i % n_steps
# add the value to the set. As sets are unique, if the value is already there nothing changes. ('r') then .add('r') stays as ('r')
if barcode[i] != '?':
step_items[step].add(barcode[i])
# if all step_items have length 0 or 1 we've found the answer. (zero means empty)
if all(len(x) in [0, 1] for x in step_items.values()):
# print(f"Unit length = {n_steps}")
return n_steps
1
u/Foldzilla 2d ago edited 1d ago
[LANGUAGE: Haskell]
Today was kinda annoying, had more of an imperative mindset concerning the solution so it took me to long :(. I use the Parser to get the sizes of the barcodes instead of running length everytime which is O(n). Does Made the code a lot more convoluted, so if it was worth it... idk... can't be asked to change it back now.
3
u/maneatingape 2d ago edited 2d ago
[LANGUAGE: Rust]
Solution
208 µs131 µs.Compact brute force. Uses iterators to checks all subsets a color at a time so that we don't need to allocate any temporary sets.
EDIT: Turned out the
lines()was taking a bunch of time, switched to.splitinstead for a nice speedup.3
u/JustinHuPrime 2d ago edited 2d ago
[LANGUAGE: x86_64 assembly]
All hail the bitset! For both solutions, I figured out that I could treat the different outputs as bits in a bitset, and then accumulate the "constraints" from the input in an accumulator to see if there's any conflict.
Part 1 and Part 2 were basically identical, except in part 1 I checked every line and summed the lengths, while part 2 just copied in the whole input ignoring newlines.
I suppose I could have optimized by interleaving the checking with the accumulating - that is, if adding a position to the accumulator would have caused a conflict, stop trying there and then. Actually, I'll go and do that...
Part 1 runs in 1 millisecond and part 2 runs in
223 milliseconds. Part 1 is9,9209,864 bytes and part 2 is9,9369,880 bytes as executable files.3
u/zogwarg 2d ago
[LANGUAGE: jq]
Part two in jq (function is mostly the same):
A bit slow ~25s but good enough for me .
3
u/ropecrawler 2d ago
[LANGUAGE: Rust] https://github.com/ropewalker/advent_of_code_2026/blob/master/src/day04.rs
3
u/aas1477 2d ago edited 2d ago
[LANGUAGE: C++]
Part 1
Part 2
most likely not optimized but basically it saves the index of each visible color, then find the lowest value so that for each index modulo the value is distinct. if 2 results are not distinct, their color should be the same.
3
u/chickenthechicken 2d ago
[LANGUAGE: C]
My part 1 code was efficient so I was able to make minimal modifications for part 2. The trick is to be lazy in evaluating the ?s, and not to try every possible combination which I think the problem text is trying to bait you into doing.
Part 1
Part 2
3
u/imperfect-fourth 2d ago edited 2d ago
[LANGUAGE: Nix]
Day 4
Greedy solution: check all intervals >= number of unique chars in the barcode.
I might try to improve on this.
3
u/Daniel_Rybe 2d ago
[LANGUAGE: Odin]
https://github.com/DanRyba253/aoc26/blob/main/day4/main.odin
Not sure if my approach is the most efficient, but both parts complete pretty much instantly, so I think it's a win.
The trick is for each possible instruction length, break the barcode into chunks of that length and look for contradictions, i.e. different letters in the same position across two different chunks.
3
u/erikade 2d ago
[LANGUAGE: Go]
brute-forced 118μs mbaM4/10/24GB
https://github.com/erik-adelbert/aoc/blob/main/2026/4/aoc4.go
3
u/jinschoi 2d ago edited 2d ago
[LANGUAGE: Rust]
Determine the minimum period that does not factor the distance between any two different colors: calculate a boolean dists array, then sieve out any periods that have a conflict starting from 1. We don't even have to fill in the colors, the period itself is the answer. This is part 2, part 1 uses the same solving function.
Edit: while I thought it was clever, the above solution always takes O( k2 ) to calculate the distance array and is disappointingly slow, ~50ms. Checking out other people's stride-based solutions, I tried this: paste and sped it up to 1.3ms on my input.
3
u/jacoman10 2d ago
[LANGUAGE: Python]
No AI used in the solving of this puzzle... I'm pretty proud in how fast and clean this turned out.
My first attempt used itertools product and was ridiculously slow... thought about the puzzle for a couple minutes and came up with this clean, much, much faster solution. After a bit of tuning, it runs in around 13ms on my machine, of which only 3ms is execution (10ms is interpreter setup)
I don't think this problem can be solved much faster without some deep inspection, but I'd love to see how someone could do it.
3
u/jhandros 2d ago
[LANGUAGE: Python]
3
u/WesternNicator 2d ago
[LANGUAGE: Anathame]
3
u/PendragonDaGreat 2d ago
[Language: CSharp C#]
Code
Not the prettiest, but it works, uses my
StringChunksFunction. It's always nice when helpers you wrote years ago come back.Also First time this year (probably not the last) I got an instinctive "fear response" just from reading the problem description.
These colors probably weren't important anywaymade me very worried for part 2, and then it was quite tame.3
u/DeadlyRedCube 2d ago
[LANGUAGE: C++23-ish]
GitHub: Initial Implementation (parts 1 & 2)
GitHub: Optimized (parts 1 & 2)
Part 1: Finished in 40:28
Oof, I got stuck on part 1 for a bit because I managed to miss the case where the only valid instruction count is the full length of the string (they just weren't being added to the total) - so the example ran fine but somewhere deep in my actual problem set it was missing that.
Once I sorted that, though, the initial algorithm boiled down to:
For every valid instruction count from 1 to barcode length (exclusive):
For each character in the barcode, test it against the relevant position in the vector (i.e. index mod instructionCount):
Part 2: Finished in 42:06
Thankfully, the algorithm for part 1 ran Part 2 in no time, so this was just "parse the problem" followed by "oh build a string that's the full thing, then run the same routine".
Optimization
The above ran in 4.47ms on my i7700, but I was able to optimize it a bit.
Instead of making a vector: For every valid instruction count from 1 to barcode length (exclusive):
For every instruction index in that count:
Iterate through the barcode, starting at the given instruction index, incrementing by the instruction count (i.e. check every position in the barcode that belongs to the given instruction index)
That runs in 1:52ms. Could probably make it faster still by doing less string building for part 2, but this is good enough for now.
3
u/runnerx4 2d ago
[LANGUAGE: Guile Scheme]
there's probably a way to do this without the string setting
3
u/sauntcartas 2d ago
[LANGUAGE: Raku]
3
u/EasyObjective360 2d ago
[LANGUAGE: OCaml]
https://github.com/0xMukesh/aoc.ml/blob/main/lib/solutions/solutions_2026/day_04.ml
3
u/urielsalis 2d ago
[LANGUAGE: Kotlin]
Did a "simple" brute force solution for part 1 with early exits, that seemed to work immediately for part 2!
Runtime is 5ms for both parts including JVM startup, 121µs for part 1 and 112µs for part 2 if its already "warmed up"
3
u/PityUpvote 2d ago edited 2d ago
[LANGUAGE: Rust]
code
Used Itertools for .dedup(), otherwise just standard Rust. Could have used something else, but this doesn't require allocating a Vec.
I really like this kind of problem, where a naive reading would lead you to an incredibly inefficient solution when an efficient solution is some analysis away. I'm glad my part 1 solution scaled well, the whole thing runs in 2ms.
3
u/dijotal 2d ago
[LANGUAGE: OCaml]
This was the first fun one. I was worried I'd have to throw in a bunch of "fail fast" checks to make Part Two work, but it finished as-is in under "four mississippis" in the interpreter -- good enough for who it's for!
3
u/muthm59 2d ago
[LANGUAGE: Perl]
These are my solution subroutines in Perl for 2026 Day 4: Perilous Pier.
See the complete runnable solution here: paste.
Part 2 was very simple to add in Perl. I expected a looong runtime for part 2, but hey!, still under a tenth of a second!
3
u/glebusharick 2d ago
[LANGUAGE: Lua]
Solution
3
u/Withered_Flower__ 2d ago
[LANGUAGE: C#]
Part1: ~0.65ms
Part2: ~0.25ms
Aoc2026/Solutions/Day04.cs at main · Withered-Flower-0422/Aoc2026
3
u/Jadarma 2d ago
[LANGUAGE: Kotlin]
Looking at the input, I saw the barcodes were very short, so I immediately went back to brute forcing. Since we are interested in the minimum length, but not the actual value, we can simply work on a pattern base, starting from just
?. I iterate over the barcode, and checking its color value. If a wildcard, leave alone. If the pattern (at respective modulo index) matches, leave alone; if it was a wildcard, now we know the actual value, and can update our candidate pattern. In case neither are wildcards and they don't match, then we have a problem: a pattern of that length cannot reproduce the barcode, we start from scratch, with the next length pattern (i.e.:??), but we can already confirm that should this pattern hold, the index we found the previous conflict must be satisfied, so we can already populate one of the pattern slots. I just loop until I found no conflicts in a run, or I have reached the original barcode length, just in case those pesky elves give me a "Penrose Barcode".When I read part two, I thought I needed to find some more optimizations due to the longer pattern, but no, barely any inconvenience, it just went from 2ms to 2.5ms. Solution for nothing, and your star for free!
AocKt Y2026D04
3
u/Outrageous72 2d ago edited 2d ago
[LANGUAGE: C#]
Part 2 was too easy, because I had setup part 1 to solve single barcodes already 😁
Refactored to not use a temp buffer and found a way to apply the new C# labeled for loop.
https://github.com/ryanheath/aoc2026/blob/main/Day4.cs
3
u/RazarTuk 2d ago
[LANGUAGE: Perl]
paste
The code's getting complicated enough that I'm not bothering to find proper Klingon names for all the variables, but I was able to get it to work. Also, full disclosure. I very much used AI to help with some of the debugging. The Klingon library isn't as bad as the Latin one, which is notoriously so buggy that you have to actively ignore the documentation, but there are still some undocumented features, like the boolean operators. The logic's fundamentally my own, and I still debugged (most of) the logic on my own, but for syntax errors, I just gave Gemini the broken line and the module source code.
The main challenge was that, despite having syntax for
continuewith a label, the Klingon Perl library does not, in fact, have any way to actually label a loop... which was a big part of my Kotlin code. And I very much felt the difference, because part 2 ran more or less instantaneously in Kotlin, but took a second or two in Perl3
u/Downtown_Tone1879 2d ago
[LANGUAGE: c]
day_4: Perilous Pier
for part one my slot and the position game was pretty calculated and thanks to '?' for making it any color that way it was easier to just hand guess the cheapest p.
for part two, glued all the line into a giant barcode and ran the same search once.
3
u/Beregolas 2d ago
[JARGON: rust]
I am currently going strong, trying to solve every day with iterators only. Today was particularly fun, working with shortcutting iterators (try_fold in
impl Barcode > check_vertical), and find over a number rangeimpl Barcode > get_min_instructions, which was not as obvious an option to me before I implemented this.Yeah, that's it... nothing particularly difficult after getting the intuition in place and dividing the work up into sensible functions.
I also find this a way more expressive and readable coding style than just nesting loops. Particularly pleased with today.
Code
3
u/e_blake 2d ago edited 2d ago
[LANGUAGE: m4]
m4 -Dpath/to/input day04.m4
Interesting twist for part 2. It wreaked HAVOC on my runtime; whereas part 1 completed in 100ms, part 2 became quadratic by virtue of m4's insistence on rescanning the ENTIRE tail of the string for every recursion, taking 11.5 seconds. Passing around 4 copies of 20k of data across 1800+ iterations of splitting off one byte at a time adds up to 4.6 gigabytes of parse effort. I suspect I may be able to come up with a byte-at-a-time solution using extra storage that avoids the re-parse penalty, for a much better final runtime.
That said, I thoroughly enjoyed the recursive nature of the solution; I only needed 3 macros to solve it, which means it should golf well:
(Edit: Oh, and I've also done a megathread-themed post later today; after jumping the gun on day 2...)
3
u/pkusensei 2d ago edited 2d ago
[LANGUAGE: Rust]
Break string into chunks and use the first chunk as model. Greedily fill '?'s in the model and match the rest of string. Code is surprisingly fast for $O(n2)$
3
u/AustinVelonaut 2d ago edited 2d ago
[LANGUAGE: Admiran]
Github
Chunked the codes into successively long fixed sized chunks, transposed the list to collect all potential collision colors together in a string, then checked that they all had no collisions. Part 2 was just concatenating the string and performing a single check.
Edit: I realized after that I could just check successive strides of an offset using a vector, and reduced runtime from 1.4s to 0.014s!
3
u/r_so9 2d ago
[LANGUAGE: F#] paste
I originally did part 1 with a brute force DFS (code in the paste above). For part 2 I got to a pretty compact solution, looking at the letter every
sizeletters to see if all of them are the same, excluding?s, and stopping at the smallestsizethat works.3
u/soylentgreenistasty 2d ago edited 2d ago
[Language: Python 3.12]
Itertools coming in clutch for chunking and re-arranging each barcode into columns.
3
u/g_equals_pi_squared 2d ago
[LANGUAGE: Odin]
paste
I want to say thanks to u/Boojum and their visualization, it really helped me understand the algorithm :)
3
u/POGtastic 2d ago
[LANGUAGE: F#]
Code
The performance on this was garbage, (20 seconds to solve Part 2) and I'm pretty sure that it was due to me using lists instead of arrays for everything. Oh well.
I am doing the following, attempting for each
nfrom 1 to the length of the barcode:n-sized chunks.Any, or is entirely comprised of repeats of a color andAny.As always, I am very irritated by F#'s stdlib with regard to stuff like
takeanddrop. It is an exception totake n xswhennis greater than the length ofxs, and in most cases it is preferable to return the empty list or sequence when that is the case. Don Syme, you betrayed me!3
u/tymscar 2d ago
[LANGUAGE: Racket]
Day 4 in racket. This puzzle was by far the best one yet.
When I first started I was thinking of ways to generate the correct string, going one by one and trying each solution. Was thinking it can't be that bad considering theres not that many colours. But then I saw my actual input and realised what a mess it would be to split into 6 each time a ? appears exponentially. Yeah, no, Im not even gonna try that.
I then I was thinking about ways to constrain the problem. Maybe smallest valid answer vs biggest valid? Well biggest is clearly the whole string, but smallest has to be the amount of different characters (this bit me in the end because I was counting ? as one, so if you have an issue, check to make sure you're not doing the same).
For Part 1 then what I ended up doing was that for each barcode, I would try so see which length is the minimum valid length. For each potential length I would then walk the string left to right, and check if my current index is the same as index mod current length im checking. If it is not then bail early (with this cool #:break syntax in racket's fold loop). Exception is when the character is a question mark. In that case I count it as valid and change it to my current character (this is important, otherwise a ? can be multiple characters). If my current value is a question mark, count is valid and go on. That's it really!
I wanted to do this functionally so spent ages looking into vectors thinking they could be immutable in racket, saw that I need a separate library, but no, all I needed was a list. It's immutable and I can change it as an accumulator in my fold.
I also found out about for/first. Super neat little trick in racket. I love how theres so many for variants that are building on the same idea. It's quite neat to realise all those things are isomorphic.
For part 2 I knew they did that to catch those who did something inefficient in part 1, so I ran it being smug, but it just ran and ran. I was stood there scared I needed to redo my logic. Started thinking about how to solve it when it finished in 15 seconds and gave me an answer. I tried it and it was right. I'll take it!
Part 1 and Part 2
3
u/Future-Custard2288 2d ago
[LANGUAGE: Chatter] Chatter is a toy language of my own devising, based on foggy memories of my first paid programming job in the long-dead language Hypertalk.
(Found a bug in Chatter today: after 2000 lines of output, it hung waiting for someone to clear its output buffer. I changed the output to non-buffered, and everything worked.)
Well, brute force worked for part 1, but not for part 2. Time to engage my few remaining brain cells...
Part 2
3
u/jwezorek 2d ago
[LANGUAGE: C++23]
Initially I did part 1 by brute force, enumerating all possible instruction sequences by turning integers into base-6 numbers with
roygbvas "numerals" and then testing whether repeating each sequence matched the barcode pattern. This worked for part 1, although it was slow. But then part 2 was basically "Okay, now the input is so big you can't do brute force, so come up with the smart way, dumbass." So I came up with the smart way and deleted my original part 1 code.The smart way is to take a barcode pattern of length n and, for each possible instruction sequence length i in [1 ... n], break the pattern into groups of i characters, padding the last group with question marks as necessary. The groups can all be satisfied by the same instruction sequence if, at each character position, there is at most one distinct non-question-mark character across all the groups.
The funny thing about this one is that the smart way ends up being much less code.
[code on github here]
3
u/fenrock369 2d ago
[LANGUAGE: rust]
The algorithm is to compare everything in a column with increasingly sized slices until all of them have just 1 colour in them, pretty much what I think most people did.
It was nice to find a completely chained non-mutating, non stack-allocating solution that works over the original input string without copying.
Solution time is 150μs for part 1, 120μs for part 2.
The second part being faster was amusing/surprising, but then it only needs to run over a single line, not add thousands of lines together.
3
u/FCBStar-of-the-South 2d ago
[LANGUAGE: Python]
paste
Standard mod based solution that everyone else seems to converge to. Was worried it wouldn't be fast enough for part 2, ran it anyways, and it took no time at all.
3
u/throwaway6560192 2d ago
[LANGUAGE: Prolog]
I thought Prolog would be a nice fit here, since the notion of unifying free variables is inherent to the whole concept of the language.
Try online: https://swish.swi-prolog.org/p/aoc2026day4_native.pl
3
u/tcbrindle 2d ago
[LANGUAGE: C++]
Today was pretty much the ideal AoC solve for me. I read the problem, thought about it for a couple of minutes, came up with an algorithm that I thought might work, coded it up and... got the star. Then part 2 just worked first time as well. Very satisfying indeed.
My algorithm is not the most efficient, but runtime is only a couple of milliseconds so it doesn't really matter.
Github: https://github.com/tcbrindle/advent_of_code_2026/blob/main/dec04/main.cpp
3
u/giacomo_hb 2d ago
[LANGUAGE: F#]
Solution
The solution of part 2 was exactly the same as part 1. I'm wondering if there was an easier way to do part 1.
3
u/Parzival_Perce 2d ago
[LANGUAGE: Python]
This required pacing around for a bit and then I figured it out, for part 2 I managed to just get my part 1 solution to work, so turns out I wrote a good one today.
3
u/ednl 2d ago
[LANGUAGE: C]
I had a rather slow solution at first where I re-initialised and built up a matching string for every new length. That was a LOT of unnecessary work. This is basically the same matching algorithm but instead of building up a string, it just checks that all colours at
index mod lengthare either the same or '?'. During part 1 where I need to find the length of each input line anyway, I also use that to copy the lines without newlines to a new string. Then for part 2 exactly the same function on that. Runtimes: M4 60 µs, M1 161 µs, Pi5 306 µs. (About 40x faster than version 1...)https://github.com/ednl/adventofcode/blob/main/2026/04.c
3
u/red_shifter 1d ago
[LANGUAGE: Python]
Topaz paste (Part 1)
3
u/Trick_Extension9400 1d ago
[LANGUAGE: Batchfile]
Part 2 is a bit tricky in Windows Batch, as the maximum string/variable length is 8,191 characters (including the command itself), while the linearised barcode is 20,000 characters long. Because of this, the barcode has to be split into ~1,000-character chunks (200 lines from the input file per chunk) for processing.
Part 1: https://github.com/PH-CC/AoC2026_WindowsBatch/blob/main/Day4Q1.bat
Part 2: https://github.com/PH-CC/AoC2026_WindowsBatch/blob/main/Day4Q2.bat
3
u/aquinas_nz 1d ago
[LANGUAGE: F#]
Nice to see the part 1 code seamlessly solved part 2
3
u/bmatcuk 1d ago
[LANGUAGE: Odin]
Link
Just checks a sliding window to see if there's a possibility of working. Increases the window size each time a solution is not found.
3
u/Akuli2 1d ago
[Language: Jou]
My Jou programming language is basically C with Python's syntax. The way how many people find this very cursed is one reason why I like it. I also have a few carefully chosen extra features like
embed_text_file()to make some things less painful.https://github.com/Akuli/jou/blob/main/examples/aoc2026/day04/part2.jou
Posting only part 2 here, because there's not much else to see in part 1. It is in the repo in case someone wants to look at it.
3
u/onrustigescheikundig 1d ago
[LANGUAGE: Scheme (R6RS)]
... with a rather large custom standard library that I've been using to play around with things like dynamic dispatch and learn about Clojure's internals.
Gitlab for Day 4
Parsing: 139 μs
Part 1: 432 μs
Part 2: 828 μs
My first misdirection this year! :O I pretty quickly coded up a generative version using lazy sequences, which generated all possible prefixes for a barcode in increasing order of length and looked for the first such that, when repeated, matched the whole barcode. This was fine for Part 1, but I was not expecting to have to concatenate everything in Part 2. The shortest prefix of the example input had 10
?s, meaning that my code would have to generate at least 610 ~ 6e7 different combinations before even reaching that point... unless... runs code anyway... yeah, no.Instead, I was reminded of something I read who-knows-where years ago about determining the key size of repeating-key XOR ciphers. The specifics differ in my improved solution, but the key (heh) is to break the text into blocks for different block sizes and then to fold the blocks into each other to get some measure of "distance" (in that case, average Hamming distance). The key size is then the argmin over the block size. For this problem, the blocks were "folded" by combining the blocks character by character. Where one of the blocks' characters was
?, the other block's character was chosen. Otherwise, the two blocks' characters had to match. If they did not (i.e., if two blocks in the input text had different characters at the same position), the algorithm short-circuited to indicate that the block length was invalid (the "distance" between blocks was infinite). With this core algorithm, all that was necessary was to scan the possible block sizes from low to high and pick the first one that succeeded.3
u/light_switchy 1d ago edited 1d ago
[LANGUAGE: Dyalog APL]
Function
ftakes one barcode at a time, so part 1 is+⌿f¨⊃⎕NGET'4.txt'1and part 2 isf∊⊃⎕NGET'4.txt'1.The key observation is that a letter at index i in the barcode is generated by the instruction at index i mod l, where l is the length of the program. For example given the example barcode
o??v???yand a program of length 5, we know that the 'y' in position 8 must be generated by an instruction at position 8 mod 5 = 3.The solution computes the indices of each letter in the pattern separately, ignoring wildcards. That looks like
⍸⍤1⊢⍵∘.=⍨∪⍵~'?', for exampleevaluates to
Which says that one letter (r, in this case) occurs at indices 1, 2, 5 and another letter (g) occurs at index 6.
If our program is of length
l, we can compute which instructions in the program are responsible for generating the letters in the barcode by computing residuals modulol. For example, iflis 3, then the characters at indices 1, 2, and 5 must be generated by instructions at (zero-based) indices 1, 2, and 2, while the character at index 6 must be generated by the instruction in position 0, which really means index 3. APL has one-based indices by default.What this is saying, is that position 1, 2, and 2 in the program (of length 3) must be the same character while position 0 (index 3) must be another character. A program is valid provided each position in the program is only required to be one character at a time.
We can check by de-duplicating within each cell
And then checking to make sure there are no duplicates at all anywhere.
The 1 means "no duplicates", which implies that a program of length 3 can print out the specified barcode. The next adjustment tests this for all possible lengths from 1 to the length of the barcode:
And then finds the index of the first length which is valid.
3
u/Radiadorineitor 1d ago
[LANGUAGE: Dyalog APL]
2
u/morgoth1145 2d ago edited 2d ago
[LANGUAGE: Python] code video
I see a color theme building up this year - we had colors on day 2 too!
Anyway, this isn't too bad - just break the barcode pattern into groups of length n and construct a set of options/candidates per character. Then merge said options/candidates together until you have one group and see if that group can be resolved/has options left at each position. If it does then great - you can set up instructions of length n for that barcode. If not - increase n and keep searching.
Part 2 isn't too bad - I was worried that my solution would bog down too much but it finished plenty fast. I'll have to optimize it though.
This problem reminds me of Picross because I've used a very similar strategy to write a Picross solver, just across all the rows/columns of a Picross grid and iteratively refining the candidates/guesses until everything is solved. (Obviously the construction of the candidate groups is quite different here and the interplay between them is different, but it reminded me nonetheless.)
Edit: optimized code
I don't know why I was doing set operations - that's silly overhead when a character/instruction is either fixed or completely unknown! Leveraging that and adding a early break for when group merging fails makes this run far, far better - ~12-13 seconds down to ~0.5 for part 2. My silly speed-solving brain misses some obvious things sometimes.
Edit 2: Even more optimized code. I didn't think of doing set operations on all the groups simultaneously until seeing u/Boojum's solution - that makes two days in a row! This is lightning speed, both due to handling all the groups together (instead of one by one), pushing it into the C layer.
2
u/Fuzzy_Patterns 2d ago
[LANGUAGE: Nim]
Bruteforce! But not the obvious one. Basically, I take every possible pattern length and then try to fit letters at
index mod <length of pattern>, if I find that I can't do that - I try the next one.Runtime: 10.5 ms
2
u/yieldtoben 2d ago
[LANGUAGE: PHP]
PHP 8.6.0 paste
Execution time: 0.019 seconds
Peak memory: 0.7505 MiB
MacBook Pro (16-inch, 2023)
M2 Pro / 16GB unified memory
2
u/Wayoshi 2d ago
[LANGUAGE: Python3] paste
I struggled to figure out how to express the problem, so I did it a brute force way at first (locking in spots where I could). Figured that'd fail for part 2, thought cycling was involved for awhile (not the case, but modulos were critical of course). The test input & output was very useful in seeing the "win condition".
Good problem for day 4/12 - obvious "infinite runtime" blocker but not too crazy to get around it.
2
u/NullT3rminated 2d ago
[LANGUAGE: Clojure]
Was getting stack overflows until I added the
doallto the result of map. This was really hard to figure out, and the error message didn't help at all2
u/acquitelol 2d ago edited 2d ago
[LANGUAGE: Elle]
Explanation: https://github.com/acquitelol/aoc2026/blob/mistress/solutions/04/explanation.md
Runs in:
GitHub: https://github.com/acquitelol/aoc2026/tree/mistress/solutions/04
2
u/ShraddhaAg 2d ago
[Language: Golang]
Brute force worked for both parts just fine, which tells me it might not work tomorrow..
https://github.com/shraddhaag/aoc/blob/main/2026/day4/main.go
2
u/TCH69 2d ago edited 2d ago
[LANGUAGE: C++]
Almost got baited into guessing each ?.
2
u/Brian 2d ago
[LANGUAGE: Python]
Went with a simple approach of trying batch sizes till one worked, by stepping through the first character of each batch and checking only one colour, or one colour and a wildcard in each batch. Takes ~180ms, so not super fast, but seems to work OK.
2
u/xoronth 2d ago
[LANGUAGE: Python]
paste
Okay, for the first part, I admit, I just violently brute-forced it... took like 20 seconds, but it did find the answer.
Then I saw part 2 and was like "ah shoot, guess that won't work", and had to redo it entirely :/
2
u/aimada 2d ago
[LANGUAGE: Lobster]
Code
Algorithm: To find the fewest instructions for a single barcode, test instruction lengths 1 up to the barcode length and pick the smallest valid period.
A repeating instruction sequence of length
Pproduces a periodic output where every indexithat has the samei mod Premainder must come from the same instruction slot.?can take any color, so they never conflict with another character.2
u/sbt4 2d ago
[Language: uiua]
github
Takes 10 seconds but works
2
u/Lindi-CSO 2d ago
[LANGUAGE: C#]
After yesterdays geometrie struggle this one was refreshingly doable on the first try. I just started growing out the pattern from the start and "repairing" the pattern while looping over chunks of the barcode.
Also a first try for part 2 with the same logic :o That's a first for me.
Part 1 & 2
2
u/maarteq 2d ago
[LANGUAGE: Python]
solution
For the first part i used bfs. just create a new string from the unique set of letters in each barcode. as soon as a result is found return the length of the result.
for part two I thought I had to use modulo arithmetic. however I figured out it could be done by slicing the list in equal length chunks, and comparing the chunks. The second part is a bit janky, I might fix it later
2
u/reddit_Twit 2d ago
[LANGUAGE: zig]
gist
today decided to share
2
u/AverageBeef 2d ago
[Language: Python 3]
Cool problem, very frustrating to lose a lot of time to just the case where there is no repeat.
Code
2
u/Daniikk1012 2d ago
[LANGUAGE: Uiua]
Iterated row-by-row, for which
tryis incredibly convenient, escaping at first mismatch. Didn't try iterating along the other axis, might have been faster, might have been slower, who knows. It's still pretty slow (3s in total for both parts on my laptop) cause it doesn't escape early when it found a size that works, instead checking all of them, but I'm not optimizing that2
u/NullQuantity325573 2d ago
[Language: Pascal]
Fun puzzle.
Approach: since the instruction pattern can only be at most the length of the original code, we can reasonably bound the search. Iterate over pattern lengths from 1 to N, where N is the length of the original code. Scan the original string for the first occurrences of each letter to seed the pattern for the given length. Then compare each character in the pattern to the original string. If we find a mismatch, halt and try the next pattern size. If we find a match, halt and return the length of the pattern. I structured the code in such a way as to avoid computationally very expensive integer division/modulo operations on a 68000.
Runs very quickly on my x86_64, less than a second for each part.
On the 68000-based Amiga, part 1 runs in 44 seconds, and part 2 takes about 3.5 minutes.
https://github.com/apprenticewiz/AOC2026/tree/main/day04
2
u/p88h 2d ago
[LANGUAGE: Nim]
Source: https://github.com/p88h/aoc2026/blob/main/src/day04.nim
Visualisation: https://youtu.be/Chlzx7Awreo
Brute force, check each period, for each period p scan character occurrences to see if it matches, but do it 8 characters at the same time (which stops each periods scan after just a few checks)
2
u/musifter 2d ago
[LANGUAGE: Perl]
For my initial part 1, I brute forced it with BFS. Queue up all the possibilities from the current length to the next using a function to return them:
To check if it's valid, I use regex (as you can see I turned '?' into '.') and just made 8 copies (as all the barcodes in my input where 2-8 characters):
Full source for that: https://pastebin.com/LJmWd3fY
That clearly wasn't going to cut it for part 2. And so I still brute forced over the lengths, but in a smarter way. The basic idea was that the paint pattern was like a "bit mask" (for bits that are base-7 not base-2). OR into its wildcards from the barcode, and check if there's a mismatch (in which case it fails and we move on to the next length). At least that's how I visualized it. The magic bit of code for that is:
Basically, we check over the barcode (and pattern mod length)... and if the pattern is still a wildcard it inherits the barcode at that position (which may also be a wildcard). After that, the pattern is still valid it the barcode is wild or the pattern and barcode match... we want the negation of that, and so we invoke De Morgan's law (not(A or B) => not A and not B).
Full source: https://pastebin.com/BV7p5fXU
2
u/xelf 2d ago edited 2d ago
[LANGUAGE: Python] NO REGEX
find the first subset that can be repeated, we don't actually care what the "?" are, just the len of that smallest pattern.
And because that was too long:
2
u/Pyr0Byt3 2d ago
[LANGUAGE: Go] [LANGUAGE: Golang]
https://github.com/mnml/aoc/blob/main/2026/04/1.go
2
u/Aoyaba-Poett 2d ago
[LANGUAGE: Rust]
Well... forgive my naming.
2
u/daanjderuiter 2d ago
[LANGUAGE: Python]
itertools my beloved
Chop up the barcode into chunks of increasing length, starting at one. If all pairwise combinations of chunks match, return the length. Otherwise, increment the length and try again.
Maybe not the most efficient way to go about it (O(n^2)) but I'm happy enough with the performance.
2
u/super_kitakami_sama 2d ago
[LANGUAGE: Go]
Initially went with brute force matching, then changed to sliding the mask along the input for part2
paste
2
u/jad2192 2d ago edited 2d ago
[LANGUAGE: Python]
https://github.com/jad2192/advent_of_code_2026/blob/master/aoc2026/day04.py
I got lucky and my solution for part 1 also worked nicely for part 2, both parts and tests run in about a tenth of a second. The key was to realize that for a sequence of length L to work you cannot have a color collision mod L* for all the known color locations.
2
u/SpaceHonk 2d ago
[Language: Swift]
Code
for all possible instruction sizes, starts with an "all wildcards" pattern and checks if it can match the entirety of the given barcode. Part 2 was trivially easy to add.
2
u/errop_ 2d ago
[Language: Python3.13]
Paste
Using
itertools.batchedanditertools.zip_longest. I put a comment in the code to explain the idea.2
u/Andreasnl 2d ago
[Language: Uiua]
Here's my original solution:
This is shorter and somewhat faster:
2
u/Positive_Concert_774 2d ago
[Language: Java]
I've left off the input reading etc, boring stuff. Calculates part 2 in 2ms.
2
u/DelightfulCodeWeasel 2d ago
[LANGUAGE: C++]
Part 1 & 2
Simple brute force, check for candidate repeat lengths 1..N until found.
Raspberry Pi Pico (RP2040):
(Combined runtime of ~2ms on PC)
2
u/akanet 2d ago
[LANGUAGE: ruby]
Ruby allows for a very nice formulation, I think:
2
u/WilkoTom 2d ago
[LANGUAGE: Rust]
Solution
Once again I fall into the trap of skimming the input data and coming to the wrong conclusion about the problem. This time, I was expecting dynamic programming, a la our trip to the Hot Springs . One of these days I won't start thinking about the wrong solution.
Once I'd worked out what I actually had to do, the problem was all of the weird edge cases I'd brought in by trying to add optimisations rather than the actual algorithim itself.
2
u/hextree 2d ago edited 2d ago
[LANGUAGE: Python]
Code
Video
Incrementally try each cycle length, and do mini sudoku logic to check if it's possible or not.
2
u/cicadanator 2d ago
[LANGUAGE: Javascript - Node JS]
I originally started working towards a breadth first search solution. This was fast enough to compute the answer for part 1. However, after seeing part 2 I knew this would not work. After getting stuck with different search algorithms for a bit I realized the goal was not to actually compute a solution but just to find the minimum cost. This means that a subset of the barcode can just be compared to the rest of the barcode to check for conflicting colors. Starting from the smallest sub-barcode and working up until I found the first working sub-barcode gave me the answer to part 2. Turns out this is also a way faster solution for part 1 as well.
https://github.com/BigBear0812/AdventOfCode/blob/master/2026/Day04.js
2
u/RudeGuy2000 2d ago
[LANGUAGE: Racket]
https://codeberg.org/chrg/aoc/raw/branch/master/2026/04.rkt
did nothing for part 2 award
2
u/Jdup1n 2d ago
[LANGUAGE: R]
Github link
To solve Part 1, I initially used a brute-force approach, but I had to rethink my approach for Part 2. So, for Part 2, I search for the smallest integer
ithrough the word such that the positions of the known letters modulo i are all distinct. This is equivalent to saying that there exists a pattern which, when repeated, forms the original word. The advantage of this approach is that it also works for Part 1, so I replaced all my code with this single function2
u/SymmetryManagement 2d ago
[Language: Java]
https://github.com/linl33/adventofcode/blob/year2026/year2026/src/main/java/dev/linl33/adventofcode/year2026/Day4.java
just a simple search over possible instruction lengths to find the min length.
Part 1 500us Part 2 2ms
2
u/aknusmag 2d ago
[LANGUAGE: Rust]
Part 1: Since the inputs were all below 6 characters I started with more of a brute force solution checking all substrings if they worked for the entire string, replacing each '?' with all characters available.
Part 2: Realized I could use the '?' in the substring and substitute it with the first character it hits. With that optimization I also no longer had to check each substring, since if they don't match the start, they won't work. Therefore I just checked the start + I increasing i by 1 until it worked for the entire string.
Solution
2
u/theMachine0094 2d ago edited 2d ago
[LANGUAGE: Rust]
Runs in under half a millisecond total for both parts:
2
u/Arctos_FI 2d ago
[LANGUAGE: C#]
That part 1 took about 3.5h to get right and then part 2 like 5min. This had just too many edge cases, so even when the provided example was correct, there were still more edge cases to think about. Well at least part 2 was easy modification.
Part 1
Part 2
2
u/musifter 2d ago
[LANGUAGE: Smalltalk (GNU)]
Basically a transcode of my Perl solution. Here it's done with extending String to have a method to calculate the number of paint instructions. Smalltalk has base-1 indexing though, so we need to adjust for that when taking the mod for our pattern:
It also lacks a lot of flow control (it has a very simple syntax that's all about message passing... which is used for a lot of the basic flow control too). This adds a little complexity to the code as we can't just "break" loops, we need to set a flag to cause the condition in the block that runs #whileTrue: to fail.
But other that that, this is the same "masking" type approach... we try the lengths in order until one works, with a state machine that runs over the barcode and copies values into the wildcards of the test pattern and fails if there's ever a forced mismatch.
Source code: https://pastebin.com/0yyz6PTX
2
u/UnicycleBloke 2d ago
[LANGUAGE: C++]
https://github.com/UnicycleBloke/aoc2026/blob/main/day04/solution.cpp
I saw what the solution right away and got a solution for the example barcodes working quickly. I then spent an age trying to understand what subtlety I had missed in the real data. Scrapped the original code and did something which turned out simpler and worked first time. Bah! Humbug!
I haven't given much thought to optimisation (yet). Part 2 took 30ms on my machine. There is a lot of string copying which I could easily refactor...
2
u/TiCoinCoin 2d ago
[LANGUAGE: Python]
Day 4
Haha, here comes the trouble! P1 took me way longer than I thought, but! P2 was already solved since I didn't use bruteforce 🥳. And just for that, I'm happy!
2
u/crumpis 2d ago edited 2d ago
[LANGUAGE: Python]
Link
A simple n3 solution: Just try to build a modular string of length cost, see if it breaks and if it does then go up a cost until we're happy with the solution.
Obviously not efficient at Part 2, takes a good 30s on my old laptop in battery mode.
Edit: abusing goto-style exception handling for performance.
Edit 2: Abusing for else instead of exception handling., forcing it into O( n2 )
2
u/mstksg 2d ago edited 2d ago
[LANGUAGE: Haskell]
https://github.com/mstksg/advent-of-code/blob/main/reflections/2026/day04.md
Here is a chance to do some neat knot-tying.
Let's say that we want to evaluate if
?g?rgy?g?rgbcan be filled at cost 3. That means that that initial?g?string has to be tiled at period 3. To get anywhere with this, we'll have to fill in the?s consistently. We can just jump back 3 from each one until we get a valid letter.Once we backfill the
?we can just literally compare the suffix with the whole backfilled string, ignoring?s:And we can see that the tiling has a failure! It tries to unify
ywithb. And note that we need the backfilling to see this, because otherwise it is not obvious if we leave those as?s:One nice way to back-fill this is to just zip the result with a lagged version of itself (in this case, three steps back) and take the lagged version if you are at a
?. The knot tying is: "assume you have the correct back-filled list alreadyres, how would you compute lagged items of it?"And yeah that should be it. Use
initsandtailsto iterate over the possible prefixes-suffixes, starting with the shorter prefixes.2
u/CEOnism 2d ago
[LANGUAGE: Javascript]
2
u/Fyver42 2d ago
[LANGUAGE: RISC-V assembly]
code
2
u/TheScown 2d ago
[LANGUAGE: Scala]
Link
2
u/NeilNjae 2d ago
[Language: Haskell]
I define the colours as a
Monoid, which allows me to combine them easily.To check a program of length k, I split the barcode into the colours at every position in the program and combine them. If any position has a
Clash, it's invalid.The shortest program is the first that's not invalid.
Full description on my blog, and code on Codeberg.
2
u/bakibol 2d ago
[LANGUAGE: Python]
Topaz's paste
2
u/s4uull 2d ago
[LANGUAGE: Rust]
This was my approach:
https://github.com/saulvaldelvira/AOC/blob/main/2026/day_04.rs
2
u/G_de_Volpiano 2d ago
[LANGUAGE: Haskell]
So the basic idea is that for a barcode to be reproduced in v instructions, there can't be two colours in the same position (modulo v). My first implementation did that in a pretty basic way, creating sets of positions, reducing them modulo v, and checking if there was any collision by comparing the number of members of their union with their total number of members. Correct, but slow, especially for part 2, as this meant applying a modulo operation to thousand of numbers, thousands of times, until I reached the correct number, so O(n²).
But why consider all numbers when all one needs is one collision ? So I switched to a loop that would exit early, reading the whole string by steps of v, exiting if I found a solution. Still O(n²) on a perverse input, but much faster in real life.
Anyhow, this gives a nice runtime
solution on github
2
u/AYM123 2d ago edited 1d ago
[LANGUAGE: Rust]
My first thought to find a pattern of length n was to fold the barcode on itself with each fold having length n.
if after folding two different colors were on top of each other, making a pattern of that length was impossible.
I later expanded on this idea with some math: all positions with indices that have the same remainder mod n must be the same color
part 1: 200µs
part 2: 140µs
github
2
u/foolnotion 2d ago
[LANGUACE: C++]
Pretty naive matching fixing loose
?in the pattern as I go, works well and runs in ~3.5mshttps://gist.github.com/foolnotion/7ffef6b8c84618c6c4147bc130db1f4f
2
u/RazarTuk 2d ago
[LANGUAGE: Kotlin]
paste
Yeah, I just brute-forced it with a lot of early exits. That's also why I'm dreading the idea of backporting this to Klingon Perl. I'd need two different flags like that. (Although if we were still playing reverse code golf...)
2
u/4th_Thunder 2d ago
[LANGUAGE: JavaScript]
Essentially trying each possible pattern length and simulating if it works by replacing the wildcards
?when there's a color at the barcode's matching position.2
u/codevogel_com 2d ago
[LANGUAGE: csharp c#]
Okay this one took me a good while to figure out. But I'm proud of my solution! https://github.com/codevogel/AdventOfCode/blob/69f7b3ed78b3664401706c633e7b66b8d6901950/2026/day4/Solver.cs
2
u/anaseto 2d ago
[LANGUAGE: Goal]
Somewhat naive solution today (about 300ms), I test increasingly longer repeating patterns until one can be made to work: I replace the "?" within a repeating pattern with placeholder values (negative numbers for those, positive ones for legible colors). And then I try to validate a pattern, replacing the negative numbers as needed, or rejecting it if there's an unsolvable mismatch.
2
u/PatolomaioFalagi 2d ago edited 2d ago
[LANGUAGE: Haskell]
2
u/ash30342 2d ago
[LANGUAGE: Java]
Day 4
Part 1 runs < 1ms, part 2 ~2ms.
I stared at this puzzle for a while. My initial gut feeling was that generating actual sequences was not the way to go and I am glad I did not.
My solution is basically to start with a sequence of length 1 of a random color (so a ?). Then walk through the barcode, replace the ? with the first color we encounter (if we do) and checking if we can make it through the whole barcode. If so we have our minimum length, otherwise try again with length + 1. More details in the comments in the code.
I love it when the solution for part 1 also works for part 2.
2
u/mschaap 2d ago edited 2d ago
[LANGUAGE: Raku]
2
u/According_Offer_2483 2d ago
[LANGUAGE: Python]
149 byte solution for day 4 part 1
143 byte solution for day 4 part 2
part 2 runs very slow, but golf isn't a fast sport anyway!
2
u/edgeman312 2d ago
[LANGUAGE: Python3]
So this wasn't a regex day, wasted too much time with that. For some reason part one still requires me to pad extra ?'s for one case and I don't have the time to figure out what's going on. Other than that it was quite a fun day, though I'm dreading the weekend.
2
u/Tipa16384 2d ago
[LANGUAGE: Python]
I still intend to implement this in Forth, but I usually use a quick Python program to solve Part 1 so I can do the Forth solution with knowledge of how both parts work, but today, Part 2 had the same solution as Part 1 so what the heck.
I read the puzzle and realized that nobody cared about the actual barcode, just the minimum size of a repeating pattern that could be folded without collisions. Lines of all '?' or '?' + 1 letter returned 1, for the others, I just use increasing slice sizes until they can be folded without collisions. Part 2 was just glomming all the input lines into one and running it through the slicer.
2
u/Royal_Pin_1971 2d ago
[LANGUAGE: PFCL]
2
u/Lispwizard 2d ago edited 1d ago
[LANGUAGE: Lisp]
2
u/ivanjermakov 2d ago
[LANGUAGE: Zig] code
No need for sets, hashmaps, etc. For each cost starting from 1, iterate barcode and check if
index%costconstraint was already set. If it was and different from current char - continue to the next cost. First cost without constraint violations is the answer. Don't forget to clear constraints array for each cost candidate.2
u/FabiSahne 2d ago edited 2d ago
[LANGUAGE: Zig]
This could do with better variable naming, but it's fairly fast and it's the first thing I thought of, which I'm pretty proud of.
paste
2
u/TheZigerionScammer 2d ago
[LANGUAGE: Python]
When I first started I thought at first "If they're small enough I could just generate every possible list of instructions in increasing size and check if one works" but I quickly though that would be dumb so I thought of something else. I realized pretty quickly that all the positions in the barcode that shared a value when modulo'd by the length of the set of instructions (so if the instructions length is 3 then the 1st, 4th, 7th, etc. positions) must al share a value or by a question mark to be valid. I thought of a couple ways to code this up, I could scan each position and modulo their index and keep the values in a dictionary or a list and voided the length of the instruction I was testing when I found a conflict, but then I realized "Can't Python automatically slice every Xth character in a string automatically?" since I had remembered someone doing that in a program here from a previous year. A quick check with the docs to get the syntax right and I figured out how to do that. So the program checks every possible length of the instruction in increasing order, takes every segmented slice and turns them into a set to deduplicate them, remove the question mark if there is one, then fails the instruction length if there's more than one character present. Increase by one until a valid length is found. This worked great but I got a wrong answer at first because it turned out I wasn't stripping the new lines form the input and they were counting as characters, ironic given what Part 2 ended up being.
This process also worked flawlessly for Part 2, I just had to concatenate the input into one line and moved the Part 1 logic into a function and ran the big line through it. Works basically instantly. Definitely wouldn't have worked if I went with my first approach of generating all the options, of course lol
Paste
2
u/xr51z 2d ago
[LANGUAGE: Julia]
I am not a coder and just do these each year as 'puzzle exercises'. Once part 2 came around I was afraid my part 1 algorithm was going to be extremely slow, but it runs in 0.64 seconds! Learning Julia and hardly using any of the strengths of the language. (Also could refactor the overlapping counter function between the two)
2
u/olamberti 2d ago edited 2d ago
[LANGUAGE: Python]
I use the number of unique colors as the lower bound for the pattern length and store the positions and colors of all known characters, ignoring the
?-s.Then I iterate through the possible pattern lengths and use modulo arithmetic to map each character to its corresponding position in the repeating pattern. The nice thing about
setdefault()is that it either assigns a color to a position or returns the already assigned one, making conflict detection quite simple.Using
all()also allows to discard an invalid pattern length as soon as the first conflict is found.For Part 2, I simply concatenate all the barcodes and apply the same function.
2
u/FlockOnFire 2d ago edited 2d ago
[LANGUAGE: Gleam]
Yesterday I learnt about BitArrays so I decided to try my hand at using them myself today.
https://github.com/janssen-io/AdventOfCode/blob/main/2026/aoc_gleam/src/day_04.gleam
Not too shabby at ~1ms for part 2 (even a tad faster than part 1).
Edit: shaved off a bit extra by just replacing newlines for part two, rather than splitting and then joining.
It's at 917us / 808us now. :)
2
u/maitre_lld 2d ago
[Language: Haskell]
https://github.com/MeisterLLD/AoC2026/blob/main/4.hs
A barcode can be represented by a pattern of length k if and only if, for every 0 ≤ r < k, all elements at indices congruent to r are equal together or equal to '?'. This leads to a brute-force approach that runs in 5 seconds for Part 2... We could probably use dynamic programming to get it down to a few milliseconds, but—meh, can't be bothered!
2
u/manu_2468 2d ago
[LANGUAGE: Python]
Actually the problem is just "what is the smallest period that generates this sequence of colors"
Part 1 solved in 6 ms, part 2 in 15 ms
A more optimized solution uses a map (but was not faster with my input):
2
u/Anceps2 2d ago
[LANGUAGE: Python]
2
u/wheresmylart 2d ago
[LANGUAGE: Python3]
Did part 1 using regular expressions because the Perl programmer in me is only mostly dead.
Went back and did it all properly for part 2. Took an increasing substring of the input from the start until it matched everything, modifying ?s as required.
Paste
2
u/hrunt 2d ago
[LANGUAGE: Python]
Code
Break the string into N-sized chunks and then look for the lowest N where the number of unique, non-'?' characters at each position in each chunk is 0 (all "?"s) or 1 (all the same). Same logic works for both parts.
2
u/siddfinch 2d ago
[LANGUAGE: Free Pascal]
With 0-based and 1-based array action going on, I was so happy to use the FP IDE debugger with breakpoints.
Day04
Is it me or is mod being used a lot this year?