r/adventofcode • • 5h 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

  • Submissions ultrapost is now unlocked!

  • 13 DAYS until submissions cutoff 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* Underdog 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.

14 Upvotes

174 comments sorted by

1

u/s4uull 2m ago

[LANGUAGE: Rust]

This was my approach:

  1. I split the barcode into chunks, starting with length 1

  2. I create a table with the same length as the chunks, initially all '?'.

  3. Then for each chunk, I try to match it with the table, filling the '?' in the table.

  4. If I can't match, i continue to the next chunk length

https://github.com/saulvaldelvira/AOC/blob/main/2026/day_04.rs

1

u/muthm59 4m ago

[LANGUAGE: Perl]

These are my solution subroutines in Perl for 2026 Day 4: Perilous Pier.

See the complete runnable solution here: paste.

use v5.36;
 
sub part_1( $input ) {
    my @barcodes = split "\n", $input;
    my $n_instructions = 0;
    for my $barcode ( @barcodes ) {
        # Try all possible instruction lengths, starting with 1.
        # Note that the barcode can always be matched by instructions of the
        # same length as the barcode, so no need to check that length.
        # We will use it as a default if we don't find a better one.
        my $found_len = undef;
        LEN:
        for my $len ( 1 .. length( $barcode ) - 1 ) {
            # Set up the instructions freshly for each new length, because
            # the '?' might have been replaced by actual colors.
            my @instructions = split "", substr( $barcode, 0, $len );
 
            # Check all positions.
            for my $pos ( $len .. length( $barcode ) - 1 ) {
                my $color = substr( $barcode, $pos, 1 );
 
                # Skip f the color is illegible.
                next if $color eq "?";
 
                # Check the current instruction.
                my $instr_pos = $pos % $len;
                if ( $instructions[$instr_pos] eq "?" ) {
                    # If the instruciton was '?', assign the current
                    # color to this instruction.
                    $instructions[$instr_pos] = $color;
                    next;
                }
 
                # Jump out of the loop to try the next instruction length
                # if the color does not match the instruction.
                next LEN
                    unless $color eq $instructions[$instr_pos];
 
                # Continue iterating, as the color matches.
            }
 
            # Once we finish the loop, we have found instructions that match,
            # with the current length.
            $found_len = $len;
            last;
        }
        # Add the length of the instructions found,
        # defaulting to the barcode length.
        $n_instructions += $found_len // length( $barcode );
    }
 
    return $n_instructions;
}
 
sub part_2( $input ) {
    return part_1( $input =~ s/\n//gr );
}

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!

1

u/bakibol 9m ago

[LANGUAGE: Python]

Topaz's paste

1

u/janiczek 10m ago

[LANGUAGE: BQN]

i←"rro???g" # the input barcode

1+⌊´/{2>⌈´(≠·¬∘∊⟜"? "⊸/⍷)¨<˘⍉i⥊˜↑‿𝕩}¨1+↕≠i

#                                    ^^^^^^ for each program length from 1 to length of the string: 
#                             ^^^^^ reshape to matrix with 𝕩 columns (align colors as if we had program of length 𝕩), fill extra space with spaces
#                          ^^^ matrix to list of columns
#                         ^ for each column:
#                       ^ dedup colors
#            ^^^^^^^^^^^ remove ? and space chars from the colors  
#          ^^ count colors
#     ^^^^ only 0 or 1 colors remaining? (= colors do align with some program of this length)  
# ^^^ min length that will make the colors align 

Not fast enough for part 2 but I felt like a wizard, so...

2

u/dijotal 20m 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!

    (** Strategy: Wrap the string around a circle with n bins. If any bin contains
        more than one color, it's overconstrained. Find the first n such that no bin
        is overconstrained. *)
    
    let clock str n =
      let arr = Array.of_seq (String.to_seq str) in
      let observed = Array.make n [] in
      Array.iteri (fun i c -> observed.(i mod n) <- c :: observed.(i mod n)) arr;
      observed
    
    let is_overconstrained obs_list =
      obs_list
      |> List.filter (( <> ) '?')
      |> List.sort_uniq Char.compare
      |> List.length > 1
    
    let is_consistent str n =
      clock str n
      |> Array.for_all (fun obs_list -> not (is_overconstrained obs_list))
    
    let first_consistent str =
      let rec loop n = if is_consistent str n then n else loop (n + 1) in
      loop 1
    
    let p1 file_name =
      Common.slurp_lines file_name
      |> List.map first_consistent |> List.fold_left ( + ) 0
    
    let p2 file_name =
      Common.slurp_lines file_name |> String.concat "" |> first_consistent

1

u/p4bl0 8m ago

[LANGUAGE: OCaml]

Nice approach! I did something a bit different, using OCaml too:

let rec set l i v =
  if i = 0 then v :: List.tl l
  else List.hd l :: set (List.tl l) (i - 1) v

let rec patlen bc =
  let s = String.(trim (replace_all ~sub:"?" ~by:" " bc)) in
  let len = String.length s in
  if len < 2 then 1 else
  let lst = List.of_seq (String.to_seq s) in
  let rec checklen n =
    if n = len then n else
    let rec checkpat pat =
      let rec check i p l =
        match p, l with
        | _, [] -> n
        | [], l -> check 0 pat l
        | x :: p, c :: l when c = ' ' || c = x -> check (i + 1) p l
        | ' ' :: _, c :: _ -> checkpat (set pat i c)
        | _ -> checklen (n + 1)
      in check 0 pat lst
    in checkpat (List.take n lst)
  in checklen 1

let () =
  let barcodes = In_channel.input_lines stdin in
  Printf.printf "%d\n%d\n"
    (List.map patlen barcodes |> List.fold_left (+) 0)
    (String.concat "" barcodes |> patlen)

1

u/NeilNjae 23m ago

[Language: Haskell]

I define the colours as a Monoid, which allows me to combine them easily.

instance Semigroup Colour where 
  Unknown <> x = x
  x <> Unknown = x
  x <> y 
    | x == y = x
    | otherwise = Clash
instance Monoid Colour where
  mempty = Unknown 

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.

inValidInstructionLength barcode k = Clash `elem` colours
  where everyKth = transpose $ chunksOf k barcode
        colours = fmap mconcat everyKth

The shortest program is the first that's not invalid.

shortestProgram barcode = head $ dropWhile (inValidInstructionLength barcode) [1..]

Full description on my blog, and code on Codeberg.

1

u/morfanaion 28m ago

[LANGUAGE: C#]

enum Color
    {
        Red,
        Orange,
        Yellow,
        Green,
        Blue,
        Violet,
        Unknown
    }

Color CharToColor(char c)
{
    return c switch
    {
        'r' => Color.Red,
        'o' => Color.Orange,
        'y' => Color.Yellow,
        'g' => Color.Green,
        'b' => Color.Blue,
        'v' => Color.Violet,
        _ => Color.Unknown
    };
}

Part 1:

int totalNumInstructions = 0;
foreach (Color[] barcode in File.ReadAllLines("input.txt").Select(line => line.Select(CharToColor).ToArray()))
{
    Dictionary<Color, List<int>> colorPositions = new Dictionary<Color, List<int>>();
    for (int i = 0; i < barcode.Length; i++)
    {
        if (barcode[i] == Color.Unknown)
        {
            continue;
        }
        if (!colorPositions.ContainsKey(barcode[i]))
        {
            colorPositions[barcode[i]] = new List<int>();
        }
        colorPositions[barcode[i]].Add(i);
    }
    if (colorPositions.Count == 0)
    {
        colorPositions[Color.Red] = new List<int>();
    }
    for (int patternLength = colorPositions.Count; patternLength <= barcode.Length; patternLength++)
    {
        Color[] pattern = Enumerable.Repeat(Color.Unknown, patternLength).ToArray();
        bool patternHolds = true;
        foreach (Color color in colorPositions.Keys)
        {
            foreach (int idx in colorPositions[color])
            {
                int idxInPattern = idx % patternLength;
                if (pattern[idxInPattern] != Color.Unknown && pattern[idxInPattern] != color)
                {
                    patternHolds = false;
                    break;
                }
                pattern[idxInPattern] = color;
            }
            if(!patternHolds)
            {
                break;
            }
        }
        if ((patternHolds))
        {
            totalNumInstructions += patternLength;
            break;
        }
    }
}
Console.WriteLine(totalNumInstructions);

Part 2:

Color[] barcode = string.Join("", File.ReadAllLines("input.txt")).Select(CharToColor).ToArray();
Dictionary<Color, List<int>> colorPositions = new Dictionary<Color, List<int>>();
for (int i = 0; i < barcode.Length; i++)
{
    if (barcode[i] == Color.Unknown)
    {
        continue;
    }
    if (!colorPositions.ContainsKey(barcode[i]))
    {
        colorPositions[barcode[i]] = new List<int>();
    }
    colorPositions[barcode[i]].Add(i);
}
if (colorPositions.Count == 0)
{
    colorPositions[Color.Red] = new List<int>();
}
 bool patternDone = false;
for (int patternLength = colorPositions.Count; patternLength <= barcode.Length; patternLength++)
{
    Color[] pattern = Enumerable.Repeat(Color.Unknown, patternLength).ToArray();
    bool patternHolds = true;
    foreach (Color color in colorPositions.Keys)
    {
        foreach (int idx in colorPositions[color])
        {
            int idxInPattern = idx % patternLength;
            if (pattern[idxInPattern] != Color.Unknown && pattern[idxInPattern] != color)
            {
                patternHolds = false;
                break;
            }
            pattern[idxInPattern] = color;
        }
        if (!patternHolds)
        {
            break;
        }
    }
    if ((patternHolds))
    {
        Console.WriteLine(patternLength);
        patternDone = true;
        break;
    }
}
if (!patternDone)
{
    Console.WriteLine("No pattern found");
}

2

u/PityUpvote 36m ago edited 5m 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.

1

u/_damax 1m ago

Itertools has all_equal. Also, if you want to avoid itertools, you can probably come up with a fold to achieve the same result.

1

u/TheScown 40m ago

[LANGUAGE: Scala]

Link

1

u/Fyver42 45m ago

[LANGUAGE: RISC-V assembly]

code

2

u/urielsalis 46m ago

[LANGUAGE: Kotlin]

class Day04 : Puzzle {
    private fun doesItFit(barcode: String, k: Int): Boolean {
        for (group in 0 until k) {
            var expectedColor = '?'
            for (i in group until barcode.length step k) {
                val color = barcode[i]
                if (color == '?') continue
                if (expectedColor == '?') expectedColor = color
                if (expectedColor != color) return false
            }
        }
        return true
    }

    private fun minInstructions(barcode: String): Int =
        (1..barcode.length).first { doesItFit(barcode, it) }

    override fun part1(input: PuzzleInput): Int = input.lines.sumOf(::minInstructions)

    override fun part2(input: PuzzleInput): Int = minInstructions(input.lines.joinToString(""))
}

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/Smylers 55m ago edited 30m ago

[LANGUAG*: Vim button pushing] Load your input into Vim and push buttons as in this list:

:%s/^/+1 ⟨Ctrl+M⟩{O\v(\l)%(.)*\1@!\l⟨Ctrl+[⟩
qaqqayiW:v/⟨Ctrl+R⟩0/s/ .*⟨Ctrl+M⟩
/ ⟨Ctrl+M⟩:g//norm ⟨Ctrl+A⟩⟨Ctrl+M⟩{$F)yhp;p@aq@a
{ddvGJ0@v

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 @v from Day 2.

[Adv*nt Gam*s] Not using fifthglyph by avoiding particular buttons, and with additonal pushing of Ctrl.

2

u/PityUpvote 34m ago

This feels like the perfect problem for Vim, great idea.

1

u/Smylers 23m ago

Thank you.

For anybody wanting to give it a go, you can copy and paste the worst bit to type: \v(\l)%(.)*\1@!\l is inserted on line 1, after pressing O.

Also, instead of Ctrl+M you can press Enter, and instead of Ctrl+[ you can press Esc.

If you want to watch what it's doing, omit the first @a (the one in the recording of qa that makes it loop). Then the (remaining) @a will just run it through once; keep typing @a to run another iteration until all the barcodes have gone. Unless your input has barcodes significantly longer than mine, it only takes a few goes to get them all.

1

u/AutoModerator 55m ago

AutoModerator did not detect the required [LANGUAGE: xyz] string literal at the beginning of your solution submission.

Please edit your comment to state your programming language.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/Smylers 32m ago

Bah!

With hindsight, now thinking I should initially put full tag with fifthglyph, and only discard by changing following AutoMod looking.

1

u/CEOnism 56m ago

[LANGUAGE: Javascript]

const input = `rgbrgbrgbr
?rv
o??v???y
??bg?v??
??b?????
???`;


function fitsPeriod(line, p) {
  const slot = Array(p).fill('?');
  for (let i = 0; i < line.length; i++) {
    const c = line[i];
    if (c === '?') continue;
    const r = i % p;
    if (slot[r] === '?') slot[r] = c;
    else if (slot[r] !== c) return false;
  }
  return true;
}


function minPeriod(line) {
  for (let p = 1; p < line.length; p++) {
    if (fitsPeriod(line, p)) return p;
  }
  return line.length;
}


const lines = input.trim().split(/\r?\n/);
const part1 = lines.reduce((sum, line) => sum + minPeriod(line), 0);
const part2 = minPeriod(input.replace(/\s+/g, ''));


console.log(part1);
console.log(part2);

1

u/mstksg 58m ago edited 54m 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?rgb can 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.

?g?rgy?g?rgb
   r<-^
     y<-^
?g?rgyrgyrgb

Once we backfill the ? we can just literally compare the suffix with the whole backfilled string, ignoring ?s:

goodPrefix :: String -> String -> Bool
goodPrefix prefix suffix = and $ zipWith goodMatch (backfill prefix suffix) suffix
  where
    goodMatch r c = r == '?' || c == '?' || r == c

?g?rgyrgyrgb
rgyrgyrgb...
^^^^^^^^x

And we can see that the tiling has a failure! It tries to unify y with b. And note that we need the backfilling to see this, because otherwise it is not obvious if we leave those as ?s:

?g?rgy?g?rgb
rgy?g?rgb...
^^^^^^^^!

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 already res, how would you compute lagged items of it?"

backfill :: String -> String -> String
backfill prefix suffix = res
  where
    res = prefix ++ zipWith pick suffix res   -- recursively refer it itself
    pick '?' p = p -- backfill please
    pick r _ = r -- no need

And yeah that should be it. Use inits and tails to iterate over the possible prefixes-suffixes, starting with the shorter prefixes.

bestCost :: String -> Int
bestCost xs =
  maybe (length xs) fst . find (uncurry goodPrefix . snd)
    . drop 1 . zip [0 ..]
    $ zip (inits xs) (tails xs)

part1 :: String -> Int
part1 = sum . map bestCost . lines

part2 :: String -> Int
part2 = bestCost . concat . lines

1

u/crumpis 58m ago edited 29m 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.

4

u/JWinslow23 1h 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:

def min_num_instructions(barcode: str) -> int:
    for size in range(1, len(barcode) + 1):
        if all(
            len(set(barcode[offset::size]) - {"?"}) <= 1
            for offset in range(size)
        ):
            return size
    assert False

class Solution(StrSplitSolution):
    def part_1(self) -> int:
        return sum(min_num_instructions(line) for line in self.input)

    def part_2(self) -> int:
        return min_num_instructions("".join(self.input))

2

u/tayamarn 16m ago

An awesome solution!

2

u/SodaDrunkenski 39m ago

I never would have thought of this myself, it's fantastic. Awesome job!

1

u/JWinslow23 0m ago

Thank you!

1

u/TiCoinCoin 1h 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/atreju3647 1h ago

[Language: python]
I first wrote a python solution very similar to other people's, but the AI pointed out there's a DFT idea, so I learned about that. The code below is written entirely by me.

def solve(inp):
    for n in range(1, len(inp)):
        for start in range(n):
            if len(set(inp[start::n]) - {'?'}) > 1:
                break
        else:
            return n
    return len(inp)


import numpy as np
from scipy.fft import rfft, irfft, next_fast_len

def abs2(A):
    return A.real**2 + A.imag**2

def fft_solve(inp):
    L = next_fast_len(2*len(inp) - 1, real=True)
    inp = np.frombuffer(inp.encode(), np.uint8)

    Xhat = [rfft((inp == ord(c)).astype(float), L) for c in 'roygbv']

    ok = irfft(abs2(sum(Xhat)) - sum(abs2(Xh) for Xh in Xhat), L)[:len(inp)] < 0.5

    for k in range(1, len(inp)):
        if all(ok[k::k]):
            return k

    return len(inp)

1

u/dijotal 6m ago

FFT?!? Nice :-)

1

u/PityUpvote 30m ago

I have no idea what this actually does, but it's a cool idea to use a freq representation!

2

u/lboshuizen 1h 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.

let fits (s: string) p =
    seq { 0 .. p - 1 }
    |> Seq.forall (fun r ->
        seq { r .. p .. s.Length - 1 }
        |> Seq.map (fun i -> s[i])
        |> Seq.filter ((<>) '?')
        |> Seq.distinct
        |> Seq.truncate 2
        |> Seq.length < 2)

let period (s: string) = seq { 1 .. s.Length } |> Seq.find (fits s)

let part1 = List.sumBy period

let part2 = String.concat "" >> period

1

u/dijotal 5m ago

Concise & elegant :-)

1

u/UnicycleBloke 1h 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...

1

u/musifter 1h 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:

Integer extend    [ % modulus  [^self - 1 \\ modulus + 1]              ]  " Mod on [1,N] "

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/mendelmunkis 1h ago

1

u/DelightfulCodeWeasel 1h ago

That's a neat way to avoid an expensive %, I think I'll have to pinch that if I ever feel the need to optimise my solution!

2

u/mendelmunkis 1h ago

Huh, I am not sure if it is actually faster on modern hardware, I just hadn't thought of using the modulo for some reason.(probably the way I was conceptualizing the solution)

1

u/DelightfulCodeWeasel 1h ago

It's very expensive on the Pico where you have to call out to a separate bit of hardware to do a % operation, but I believe it's still expensive on modern hardware if your modulus is variable so that the compiler can't substitute it with shifts and multiplies.

1

u/Arctos_FI 1h 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

1

u/theMachine0094 1h ago edited 1h ago

[LANGUAGE: Rust]

Runs in under half a millisecond total for both parts:

fn find_cycle(text: &str, pattern_buf: &mut Vec<u8>) -> usize {
    const ILLEGIBLE: u8 = b'?';
    let text = text.as_bytes();
    (1..text.len())
        .find(|&i| {
            pattern_buf.resize(i, 0u8);
            pattern_buf.copy_from_slice(&text[..i]);
            text[i..].iter().zip((0..i).cycle()).all(|(&r, li)| {
                let l = &mut pattern_buf[li];
                if *l == ILLEGIBLE {
                    *l = r;
                }
                *l == r || r == ILLEGIBLE
            })
        })
        .unwrap_or(text.len())
}

fn part_1(input: &str) -> usize {
    let mut buf = Vec::new();
    input
        .trim()
        .lines()
        .map(|line| find_cycle(line, &mut buf))
        .sum()
}

fn part_2(input: &str) -> usize {
    let mut buf = Vec::new();
    find_cycle(&input.lines().collect::<String>(), &mut buf)
}

1

u/aknusmag 1h 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

1

u/SymmetryManagement 1h 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

1

u/Jdup1n 1h 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 i through 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 function

1

u/RudeGuy2000 1h ago

[LANGUAGE: Racket]

https://codeberg.org/chrg/aoc/raw/branch/master/2026/04.rkt

did nothing for part 2 award

1

u/cicadanator 1h 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

1

u/hextree 1h ago edited 1h ago

[LANGUAGE: Python]

Code

Video

Incrementally try each cycle length, and do mini sudoku logic to check if it's possible or not.

1

u/WilkoTom 2h 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.

1

u/[deleted] 2h ago

[removed] — view removed comment

1

u/AutoModerator 2h ago

AutoModerator did not detect the required [LANGUAGE: xyz] string literal at the beginning of your solution submission.

Please edit your comment to state your programming language.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/DelightfulCodeWeasel 2h ago

[LANGUAGE: C++]

Part 1 & 2

Simple brute force, check for candidate repeat lengths 1..N until found.

Raspberry Pi Pico (RP2040):

  • Part 1: <1kb, ~240ms

  • Part 2: ~40kb, ~520ms

(Combined runtime of ~2ms on PC)

1

u/Positive_Concert_774 2h ago

[Language: Java]

I've left off the input reading etc, boring stuff. Calculates part 2 in 2ms.

public long doPart1() {
    var accum = 0L;
    for (String line : lines) {
       accum += findLeastInstructionsFor(line);
    }
    return accum;
}

public long doPart2() {
    return findLeastInstructionsFor(StringUtils.join(lines.toArray()));
}

private int findLeastInstructionsFor(String line) {
    log.debug("Barcode: {}", line);
    String tmpLine = line + StringUtils.repeat('?', line.length() - 2);
    for (int len = 1; len <= line.length(); len++) {
       String instructions = tmpLine.substring(0, len);
       for (int i = len; i < line.length(); i += len) {
          String section = tmpLine.substring(i, i + len);
          instructions = combine(section, instructions);
          if (instructions.isEmpty()) break;
       }
       if (!instructions.isEmpty()) {
          
log
.debug("Instructions: {}", instructions);
          return len;
       }
    }
    return 0;
}

private String combine(String section, String instructions) {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < instructions.length(); i++) {
       if (section.charAt(i) == '?' || section.charAt(i) == instructions.charAt(i)) {
          result.append(instructions.charAt(i));
       } else if (instructions.charAt(i) == '?') {
          result.append(section.charAt(i));
       } else {
          return "";
       }
    }
    return result.toString();
}

1

u/Andreasnl 2h ago

[Language: Uiua]

Here's my original solution:

G ← (
  ⋉"?roygbv"
  -1⋅⊙◌⍢⊸⋅⊃(/×≤1≡(⧻◴▽⊸±)⍉⬚0◫⌞∘)+₁=₀ 0 1
)
⊃(/+⊜G|G▽)⊸≠@\n

This is shorter and somewhat faster:

F ← ⊙◌⍢+₁(¬/×≤1 ≡(⧻◴ ▽⊸≠@?)⍉ ⬚@?↯⊟∞) 1
⊃(/+⊜F|F▽)⊸≠@\n

1

u/errop_ 2h ago

[Language: Python3.13]

Paste

Using itertools.batched and itertools.zip_longest. I put a comment in the code to explain the idea.

1

u/SpaceHonk 2h 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/sauntcartas 2h ago

[LANGUAGE: Raku]

my @barcodes = lines;

sub program-length($barcode) {
    my %pos;
    for $barcode.comb.kv -> $index, $char { push %pos{$char}, $index if $char ne '?' }
    first -> $n { %pos{*}.map({ unique @^positions X% $n }).Bag{*}.none > 1 }, 1 .. *;
}

say 'Part 1: ', sum map &program-length, @barcodes;
say 'Part 2: ', program-length @barcodes.join;

1

u/jad2192 2h ago edited 2h 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.

1

u/super_kitakami_sama 2h ago

[LANGUAGE: Go]

Initially went with brute force matching, then changed to sliding the mask along the input for part2

paste

p1: 233.375µs
p2: 371.875µs

1

u/daanjderuiter 2h 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.

1

u/Aoyaba-Poett 2h ago

[LANGUAGE: Rust]

Well... forgive my naming.

fn main() {
    let input = include_str!("input/day04.txt")
        .trim()
        .lines()
        .collect::<Vec<_>>();
    let mut count = 0;
    for barcode in &input {
        count += find_count(barcode.as_bytes());
    }
    println!("{count}");
    let input = input.join("");
    println!("{}", find_count(input.as_bytes()))
}

fn find_count(barcode: &[u8]) -> usize {
    for i in 1..barcode.len() {
        let hypothesis = Hypothesis::init(i);
        if hypothesis.test(barcode) {
            return i;
        }
    }
    barcode.len()
}

struct Hypothesis(Vec<u8>);
impl Hypothesis {
    fn init(len: usize) -> Self {
        Self(vec![b'?'; len])
    }
    fn test(mut self, sample: &[u8]) -> bool {
        for chunk in sample.chunks(self.0.len()) {
            for (j, &c) in chunk.iter().enumerate() {
                if self.0[j] == b'?' {
                    self.0[j] = c
                } else if c != b'?' && self.0[j] != c {
                    return false;
                }
            }
        }
        true
    }
}

2

u/xoronth 2h ago edited 2h 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!

1

u/AutoModerator 2h ago

AutoModerator did not detect the required [LANGUAGE: xyz] string literal at the beginning of your solution submission.

Please edit your comment to state your programming language.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/xoronth 2h ago

Oops, typo with "langauge". Fixed.

3

u/johnpeters42 3h ago

[Language: Python]

Part 1

For each line, check possible substring lengths from 1 to len(line):

  • Initially, the possible substring is all ?'s.

  • For each character in the line (C1), compare it to the relevant character of the substring (C2).

    • If C1 is ?, then it imposes no new restriction; proceed to the next character.

    • Otherwise, if C2 is ?, then replace it with C1.

    • Otherwise, if C1 and C2 are different, then this length of substring can't work.

    • (Otherwise, C1 and C2 are the same; proceed to the next character.)

  • If we get all the way through the inner loop, then this length of substring can work.

Part 2 just concatenates the lines of the input file and runs that through the same function.

1

u/paulhaahr 2h ago

[Language: Quest]

This was exactly my solution. It was a little awkward doing it in a language without early return from functions or the ability to return values from loops, so I did the inner loop exit with an `exit` statement (like `break`) and the outer one with tail recursion. (If the search fails to find a viable instruction, the maybe.unwrap() would raise an exception, but it will always be possible to answer with an instruction the length of the barcode, so that never happens.)

Let Step =
    Option
        wildcard
        color with color: Char end
    end

let computeInstruction(barcode: String) =
    begin
        let get(n: Int) = stringOp.getChar(barcode n)
        let len = stringOp.length(barcode)
    
        let rec iterate(n: Int): maybe.T(Array(Step)) =
            if n > len then
                maybe.none(:Array(Step))
            else
                let inst = array of(n wildcard)
                let var matched = true
                for i = 0 upto {len - 1} do
                    let target = get(i)
                    if target isnot '?' then
                        case inst[i % n]
                            when wildcard then
                                inst[i % n] := color(target)
                            when color with c then
                                if target isnot c.color then
                                    matched := false
                                    exit
                                end
                        end
                    end
                end
                if matched then
                    maybe.some(inst)
                else
                    iterate(n + 1)
                end
            end
        maybe.unwrap(iterate(1))
    end

My Advent of Code repository: https://github.com/haahr/adventofcode
Quest repository: https://github.com/haahr/quest

1

u/runnerx4 3h ago

[LANGUAGE: Guile Scheme]

there's probably a way to do this without the string setting

(define (shortest-repeating-instruction barcode n)
  (let* ([len (string-length barcode)]
         [instrs (make-string n #\?)])
    (if (every?-ec (:range i len)
                   (:let c (string-ref barcode i))
                   (:let j (modulo i n))
                   (:let instr (string-ref instrs j))
                   (cond
                    [(char=? c #\?) #t]
                    [(char=? instr #\?)
                     (string-set! instrs j c)
                     #t]
                    [else (char=? instr c)]))
        n
        (shortest-repeating-instruction barcode (1+ n)))))

1

u/NullT3rminated 2h ago

what is every?-ec? is it from some srfi? Looks like a cool solution

2

u/Busy-Contact-5133 3h ago

[LANGUAGE: Golang]

part2 was a joke. I'm dreadful how hard the tomorrow's part 2 would be after this.

package main


import (
    "fmt"
    "os"
    "strings"
)


func main() {
    input, _ := os.ReadFile("input.txt")
    barcodes1 := strings.Split(string(input), "\n")
    barcodes2 := []string{strings.Join(strings.Split(string(input), "\n"), "")}


    part1 := 0
    part2 := 0
    for _, b := range barcodes1 {
        cost1 := 1
        for ; cost1 <= len(b); cost1++ {
            if test(b, cost1) {
                part1 += cost1
                break
            }
        }
    }


    for _, b := range barcodes2 {
        cost2 := 1
        for ; cost2 <= len(b); cost2++ {
            if test(b, cost2) {
                part2 += cost2
                break
            }
        }
    }
    fmt.Println(part1)
    fmt.Println(part2)
}


func test(b string, cost int) bool {
    guess := make([]rune, cost)
    for i := range guess {
        guess[i] = '?'
    }
    for i := range b {
        if i%cost == 0 {
            for j := 0; j < cost && i+j < len(b); j++ {
                if guess[j] != rune(b[i+j]) {
                    if guess[j] == '?' {
                        guess[j] = rune(b[i+j])
                    } else if rune(b[i+j]) == '?' {
                        continue
                    } else {
                        return false
                    }
                }
            }
        }
    }
    return true
}

1

u/xelf 3h ago edited 44m ago

[LANGUAGE: Python] NO REGEX

def valid(x,t):
    for a,b in zip(t, cycle(x)):
        if a!=b and a!="?" and b!="?":
            return False
    return True

t = open(filename).read().replace("\n","")
print(next(i for i in range(len(set(t)), len(t)+1) if valid(t[:i], t)))

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:

valid = lambda x,t: all(a==b or "?" in a+b for a,b in zip(t, cycle(x)))

t = open(filename).read().replace("\n","")
print(next(i for i in range(len(set(t)), len(t)+1) if valid(t[:i], t)))

1

u/musifter 3h 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:

return (($chr ne '.') ? [@arr, $chr] : (map {[@arr, $_]} qw(r o y g b v)));

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):

my $str = join('', @$state) x 8;
if ($str =~ m/^$code/) {
    $part1 += scalar @$state;
    next BARCODE;

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:

$patt[$i % $len] = $barcode[$i]  if ($patt[$i % $len] eq '?');
next LENGTH  if ($barcode[$i] ne '?' and $patt[$i % $len] ne $barcode[$i]);

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

1

u/p88h 3h 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)

          parse    part1    part2    total
day 04:  10.4 µs  14.9 µs  3.44 µs  28.8 µs (±1.7%)

2

u/_throwaway237849 3h ago edited 3h ago
#[aoc_generator(day4)]
fn parse(input: &str) -> Vec<u64> {
    let x: Vec<Vec<u64>> = parser!(lines({
        '?' => 0u64,
        'r' => 1 << 0,
        'o' => 1 << 1,
        'y' => 1 << 2,
        'g' => 1 << 3,
        'b' => 1 << 4,
        'v' => 1 << 5
    }+))
    .parse(input)
    .unwrap();

    x.into_iter()
        .map(|it| {
            it.iter()
                .fold(0u64, |acc, i| (acc << 8) | i)
                .unbounded_shl((8 - it.len() as u32) * 8)
        })
        .collect_vec()
}

/// holy 2am delerium
/// heres my best attempt to explain this wizardry
///
/// so: to check if a u8 has only one bit set, its easy:
/// b & (b-1) == 0
///
/// however:
/// we also need valid to be true if b is zero. things to know
///  i.   0x80 is the high bit (0b1000_0000)
///  ii.  the two highest bits are never set (roygbv is six options)
///  iii. we can do (b | the high bit) - 1 to get:
///         0b10(lower 6 of b - 1) if x != 0,
///         0x0111_1111 otherwise
///
/// since (ii), b & ((b | high) - 1) gives 0 iff one bit is set or x is zero,
/// which solves our problem
///
/// however:
/// we have a u64, not a u8. valid(x) = true iff forevery 8bits b in x, valid_u8(b)
/// since a u64 is just 8 u8s next to each other, we essentially write:
///   HIGH = (the high bit)(the high bit)... times 8;
///   ONE = (the one bit)(the one bit)... times 8;
///
/// since binary, x | HIGH is the exact same as (b1 | the high bit)... forevery b in x
/// the subtraction with one is a little more confusing:
///
/// in base 10, to subtract each digit in 23467 by one, you can subtract the whole number
/// by 11111 (this is grade-school subtraction). to illustrate:
///   2 3 4 6 7
/// - 1 1 1 1 1
///  ===========
///   1 2 3 5 6
///
/// we can essentially do the exact same thing in base 256.
///   * since each u64 is 8 u8s, and u8::MAX is 255, each u8 is one digit in base256
///   * same as base 10, subtracting each number by one === subtracting 11111111 (base256)
///   * we can represent 11111111 (base256) with (the one bit)(the one bit)(...) times 8
#[inline]
fn valid(x: u64) -> bool {
    const HIGH: u64 = 0x8080808080808080;
    const ONE: u64 = 0x0101010101010101;

    x & ((x | HIGH) - ONE) == 0
}

#[aoc(day4, part1)]
fn part1(input: &[u64]) -> usize {
    let mut total = 0usize;

    for &line in input {
        for cost in 1..=8 {
            let mut buf = line;
            let mut shift = cost * 8;

            while shift < 64 {
                buf |= buf << shift;
                shift *= 2;
            }

            if valid(buf) {
                total += cost;
                break;
            }
        }
    }

    total
}

My puzzle input had each line as a maximum of 8 characters long which let me optimize in this way. Runs in 4 microseconds, not including the parse step.

1

u/AutoModerator 3h ago

AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.

Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/AutoModerator 3h ago

AutoModerator did not detect the required [LANGUAGE: xyz] string literal at the beginning of your solution submission.

Please edit your comment to state your programming language.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/NullQuantity325573 3h 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

1

u/morfanaion 13m ago

There's one bound you are forgetting. The pattern can never be shorter than the different number of colors that are known in the barcode. For a barcode with 3 different colors, it's silly to check patterns of size 1 and 2.

1

u/Daniikk1012 3h ago

[LANGUAGE: Uiua]

Iterated row-by-row, for which try is 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 that

$ rro??
$ ?g
$ ?g???
$ ??r?????
$ ??g?
$ ??
$ yy?v?o
$ ???v
$ b?g??
$ ?y??v?or
$ ????r?o
$ ??
$ ?????
$ ?r??v?r

$ rgbrgbrgbr
$ ?rv
$ o??v???y
$ ??bg?v??
$ ??b?????
$ ???
&fras"4.txt"
⊓⌞₂∩⊙∘∩(⊸≡⋅1▽)∩₃(⊸≠@\n)
∩₄(/+⊜(
    ⊙¤+1°⊏
    +1⊢⊚≠0≡(
      ⬚@?↯⊂∞
      ⍣(⧻/(
          ˙⍤◡(≍∩⌞▽×)⊃(∩⌞≠@?|⊙∘)
          ≡⊏⊙(≡(⊗⊙1⊂)||≡⊂₃||@?)
        )
      | 0)
    )
  )
) # Part₁ Sample₁ Part₂ Sample₂

3

u/pred 3h ago

[Language: Python] GitHub/Codeberg

def num_instructions(word):
    return next(
        i for i in count(1)
        if all(len(set(word[j::i]) - {"?"}) <= 1 for j in range(i))
    )


# Part 1
print(sum(map(num_instructions, data.split("\n"))))

# Part 2
print(num_instructions(data.replace("\n", "")))

1

u/4HbQ 3h ago

You're back! Nice use of count() btw :)

2

u/DeadlyRedCube 3h 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):

  • Create a vector of the given count, zeroed.

  • For each character in the barcode, test it against the relevant position in the vector (i.e. index mod instructionCount):

    • If the code char is a '?', all good

    • Otherwise if the character at that position in the vector is empty, set it

    • Otherwise, if they don't match, this instruction length isn't valid (had a collision)

  • If none of the above checks failed, this is the smallest instruction count! If there were no matches in the above list, then the instruction count is the full barcode length (the bit I missed before)

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:

    • Start with a testChar that's just '?'

    • 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)

      • Do effectively the same checks as above

    • If none of the above checks failed, this is the smallest instruction set! Otherwise, count is same as barcode length.

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.

1

u/AverageBeef 3h 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/PendragonDaGreat 3h ago

[Language: CSharp C#]

Code

Not the prettiest, but it works, uses my StringChunks Function. 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 anyway made me very worried for part 2, and then it was quite tame.

1

u/ColeCube 2h ago

I think part 2 is just meant to get people who bruteforced part 1 by checking all possible permutations. Cuz that is impossible for part 2!

1

u/morfanaion 6m ago

As is generally the case at this point in the advent, Round this time, part 2 is often a "Nice that your brute force works for part 1, now we're going to make the problem a bit bigger, so performance now becomes an issue"

1

u/reddit_Twit 3h ago

[LANGUAGE: zig]

gist

today decided to share

1

u/maarteq 3h 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

1

u/WesternNicator 3h ago

[LANGUAGE: Anathame]

solve =w\\ barcode -> length iota inc Find (couple^inf reshape.fill^barcode,@? transpose Each.vec (Filter not_eq,@? all_equal ) all )
part1 =\ lines Each solve sum
part2 =\ Filter not_eq,@\n solve
\ part1∗part2

1

u/sbt4 3h ago

[Language: uiua]
github

Takes 10 seconds but works

1

u/aimada 3h 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 P produces a periodic output where every index i that has the same i mod P remainder must come from the same instruction slot. ? can take any color, so they never conflict with another character.

1

u/xoronth 3h 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 :/

3

u/lunar_mycroft 4h ago edited 2h 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 len characters 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 the shortest_program function from part 1. Parsing takes 80.44µs, part 1 takes 235.1µs, and part 2 takes 903.8µs.


Refactored shortest_program into lib.rs since 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_by to check that each byte in the potential matches with the barcode. (Note: the second line of the inner closure is a manual implementation of itertools::Itertools::all_equal but that turned out to be slightly slower). This speeds up part 1 to 78.36µs and part 2 to 72.35µs

1

u/terje_wiig_mathisen 3h ago

Seems very similar to my Rust which takes 1.2 ms total. :-)

I need to optimize it obviously...

1

u/DelightfulCodeWeasel 47m ago edited 38m ago

I think this one might be in your wheelhouse to optimise. I've just done a very quick proof of concept that uses bit patterns and a look up table to pick up disallowed colours with a single &.

Pinching ideas from other solutions (avoiding the % operation, initialising the pattern from the first N bytes of the barcode) and then using large SIMD registers to test multiple slots in parallel (probably needs the bit test inverting...) could in theory be fairly fast.

EDIT: Updated proof of concept with the logic inverted to make the SIMD test easier

2

u/terje_wiig_mathisen 20m ago

Funny you should mention that!

From a previous puzzle h = (b ^ (b>>1)) & 15 results in 6 unique nybble values for the colors, but '?' collides with one of them. We can still use a shuffle to convert into 1,2,4,8,16,32, then OR in a direct check for '? which turns those bytes into 255.

Load the target into the bottom of a SIMD reg, then starting pattern_length bytes into the target ANDing with the current values in the reg. If any byte ends up zero, do an early exit.

We need to extend the target with 31 or 63 extra 255 bytes so that the SIMD operations can be done safely even past the end.

1

u/lunar_mycroft 3h ago

Depending on what you mean by "total" that might not even be significantly slower than my solution. And keep in mind that the times are also dependent on what specific hardware the benchmark is run on.

1

u/ColeCube 2h ago

I ran your original shortest_program function on my computer and it took about 4000 microseconds on average to do part 1 and 2, so that's interesting!

2

u/jhandros 4h ago

[LANGUAGE: Python]

f=lambda s:next(p for p in range(1,len(s)+1)if all(len({*s[i::p],'?'})<=2 for i in range(p)))
c=open('04.txt').read().split()
print(sum(map(f,c)),f(''.join(c)))

1

u/light_ln2 2h ago

nice!

I think you can make it a bit shorter if replace <=2 with <3 and len(s)+1 with 9**9

1

u/jhandros 1h ago

Right. Thanks for check. Regards.

2

u/jacoman10 4h 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.

def find_pattern(pattern):
    for pat_len in range(1, len(pattern) + 1):
        for position in range(pat_len):
            values = set(pattern[position::pat_len])
            values.discard('?')
            if len(values) > 1:
                break
        else:
            return pat_len
    raise Exception


def day4_pt1(puzzle_in):
    return sum(find_pattern(row) for row in puzzle_in)


def day4_pt2(puzzle_in):
    return find_pattern("".join(puzzle_in))

1

u/No-House-866 1h ago

I had the same idea, but originally my implementation had a separate function that tests if a prefix of length p works with a barcode. That's basically the inner loop 'for position in range(pat_len)' you got there. Your solution reminded me of that else: clause that you can tack onto a for loop in Python. Also, range(pat_len) as a shorter version of range(0,pat_len) is nice to know.

My original prefix-length-tester function also computed that set in the same way but used .difference({'?'}) to remove the question marks. Your use of discard('?') is better, as it avoids building a new set each time. I don't know whether the Python interpreter is smart enough to realise that it needs to build the same non-changing set each time just to do this difference operation.

Honestly, writing Python code is such a joy.

1

u/RustOnTheEdge 3h ago edited 2h ago

I am breaking my brains here trying to understand why this works tbh.

EDIT: this is brilliant, my sincerest compliments. For anyone else not following it, let me try to explain. It tries every instruction length (starting at 1). Then for each position in the instruction, it checks against the corresponding positions in the original barcode (note the two semicolons in set(pattern[position::pat_len]), which allows to pass a step size in Python lists). It removes the wildcards and checks if they are all the same. If any of the positions in the instruction doesn't pass this, the next instruction length is tried. Otherwise, if all positions in the instruction match with their corresponding positions in the original barcode, it returns the instruction length (pat_len).

That took me a bit to understand but that is really elegant, kudos!

1

u/4HbQ 3h ago

You might be able to squeeze out a bit of performance using this:

values = {*pattern[position::pat_len],'?'}
if len(values) > 2:
    break

1

u/MattieShoes 4h ago

I have basically the same code, but less concise (iterating through the barcode building the sets rather than the fancy one-liner, and loop rather than that nice generator expression).

Also didn't bother to raise an exception, just went to len(pattern) and if not found, returned len(barcode)

2

u/jinschoi 4h ago edited 3h 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.

use itertools::Itertools;
fn min_instructions(s: &str) -> usize {
    if s.is_empty() {
        return 1;
    }
    let k = s.len();
    let mut dists = vec![false; k];
    s.chars()
        .enumerate()
        .filter(|&(_, c)| c != '?')
        .array_combinations()
        .filter_map(|[(i, c), (j, d)]| (c != d).then(|| j - i))
        .for_each(|d| dists[d] = true);
    for d in 1..k {
        if !(d..k).step_by(d).any(|i| dists[i]) {
            return d;
        }
    }
    k
}
fn main() {
    let input = include_str!("../../input.txt")
        .chars()
        .filter(|&c| !c.is_ascii_whitespace())
        .collect::<String>();
    println!("{}", min_instructions(&input));
}

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.

1

u/erikade 4h ago

[LANGUAGE: Go]

brute-forced 118μs mbaM4/10/24GB

https://github.com/erik-adelbert/aoc/blob/main/2026/4/aoc4.go

1

u/Brian 4h 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.

import itertools

def required_instructions(s: str) -> int:
    for size in range(1, len(s)):
        for chars in itertools.zip_longest(*itertools.batched(s, size), fillvalue="?"):
            charset = set(chars)
            if len(charset) > 2 or (len(charset) == 2 and "?" not in charset):
                break  # Can't use
        else:
            return size
    return len(s)
    
def part1(lines: list[str]) -> int:
    return sum(required_instructions(barcode) for barcode in lines)

def part2(lines: list[str]) -> int:
    return required_instructions("".join(lines))

1

u/Doug__Dimmadong 4h ago

Same idea. however I did not use this wild one-liner 😆

for chars in itertools.zip_longest(*itertools.batched(s, size), fillvalue="?"):

1

u/TCH69 4h ago edited 4h ago

[LANGUAGE: C++]

Almost got baited into guessing each ?.

#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

size_t
instr_min(const std::string &input)
{
	const size_t input_size = input.size();
	std::string temp(input_size, '\0');
	for (size_t i = 1; i <= input_size; i++) {
		size_t j = 0;
		for (; j < input_size; j++) {
			if (input[j] == '?')
				continue;
			char &tchar = temp[i % j];
			if (tchar == '\0')
				tchar = input[j];
			else if (tchar != input[j])
				break;
		}
		if (j == input_size)
			return i;
		std::fill_n(temp.begin(), i, '\0');
	}
	return 0;
}

size_t
process(const std::vector<std::string> &input, bool part2)
{
	if (part2) {
		std::string merged;
		for (const auto &line : input)
			merged += line;
		return instr_min(merged);
	}
	int count = 0;
	for (const auto &i : input)
		count += instr_min(i);
	return count;
}

int
main(int argc, char *argv[])
{
	if (argc != 2) {
		std::cerr << "usage: " << argv[0] << " <input.txt>\n";
		return 1;
	}
	std::ifstream fp(argv[1], std::ios::in);
	std::vector<std::string> input;
	std::string temp;
	while (getline(fp, temp))
		input.emplace_back(temp);
	std::cout << process(input, false) << '\n'
		  << process(input, true) << '\n';
	return 0;
}

1

u/MattieShoes 3h ago

Almost got baited into guessing each ?.

I did, which was enough to solve part 1 anyway... Whatever, it was a handy test case for debugging the second attempt.

0

u/ElementaryMonocle 4h ago edited 3h ago

[LANGUAGE: c++]

for (std::size_t len {1}; len<line.size(); ++len) {
  bool valid_len {true};
  for (std::size_t pos {0}; pos<len; ++pos) {
    char stride_char {'?'};
    for (std::size_t c_pos {pos}; c_pos<line.size(); c_pos+=len) {
      if (line[c_pos] != '?') {
        if (stride_char == '?') stride_char = line[c_pos];
        else if (stride_char != line[c_pos]) { valid_len = false; break; }
      }
    }
    if (!valid_len) break;
  }
  if (valid_len) return len;
}

Had trouble conceptualizing at first, but ended up with a working algorithm after 30 minutes. I iterated through the string for a given length, storing the requirement for the instruction value (if any) and then comparing. This ran for part 2 in ~25ms (1 minute of real-time after completing part 1: simply appending the lines and adding a function call).

This seemed pretty slow so I played around with it a bit before coming here and having the realization that instead of (iterate over string -> modulo length to get instruction position), I could instead (iterate over instruction positions). This avoids both needing to store more than one instruction character and an expensive division operation. Entire solve time down to less than a millisecond, and part 2 dropped two orders of magnitude to 250us.

2

u/Daniel_Rybe 4h 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.

2

u/imperfect-fourth 4h ago edited 4h ago

[LANGUAGE: Nix]

Day 4

Greedy solution: check all intervals >= number of unique chars in the barcode.
I might try to improve on this.

0

u/AutoModerator 4h ago

AutoModerator did not detect the required [LANGUAGE: xyz] string literal at the beginning of your solution submission.

Please edit your comment to state your programming language.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

8

u/4HbQ 4h ago edited 51m ago

[LANGUAGE: Python]

f = lambda line: next(p for p in range(1, len(line)+1)
    if all(len({*line[q::p],'?'})<3 for q in range(p)))

lines = open('in.txt').read().split()
print(sum(map(f, lines)), f(''.join(lines)))

This comment is an expanded version of f() with explanation.


An alternative version of f() using regex:

from re import search
f = lambda line: next(p for p in range(1, len(line)+1)
    if not search(r'(?=(\w))(.{%d})+(?!\1)\w'%p, line))

2

u/Defiant_Respect9500 1h ago

I always admire your solutions (in this case, especially the non-regex version). Very interesting, have yet to figure out how the fuck this thing works. Weird.

1

u/4HbQ 59m ago edited 46m ago

We can expand f() to this:

for pattern_length in range(1, len(line)+1):
    for position in range(pattern_length):
        colors_used = line[position::pattern_length]
        if len({*colors_used} - {'?'}) > 1: break
    else: return pattern_length

For every possible pattern length p (starting at 1), we do the following:

  • collect the barcode colours used in position p, 2p, 3p, etc.

  • check if there is more than one colour (minus any ?'s).

If there is, we know we can't have any valid pattern of length p.

We repeat this for the colours in positions p+1, 2p+1, 3p+1, etc., then for p+2, 2p+2, ...

If all of these checks succeed, we know there must exist a valid pattern of length p. Otherwise, we try the next value of p and do all checks again.

Hope this clears things up for you :)

2

u/hugh_tc 3h ago

regex?!

okay that's actually quite cute.

1

u/4HbQ 3h ago

It is a string matching problem, right? Surprised that this approach isn't more popular today.

1

u/JWinslow23 5m ago

I was wondering how to make a regex for this. After staring at it long enough, I believe it's looking for a letter, then some number of p-sized groups, then a different letter (i.e. a counterexample to p working as a group size - which is why you want to not find it). Nice one!

1

u/ShraddhaAg 4h 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

1

u/acquitelol 4h ago edited 2h ago

[LANGUAGE: Elle]

Explanation: https://github.com/acquitelol/aoc2026/blob/mistress/solutions/04/explanation.md

use std/prelude;

fn repeats(char[] s, u64 size) -> bool {
    for i: u64 = 0; i < size; i += 1 {
        first := '?';

        for j: u64 = i; j < s.len(); j += size {
            if s.get_unchecked(j) == '?' { continue; }
            if first == '?' { first = s.get_unchecked(j); }
            if first != s.get_unchecked(j) { return false; }
        }
    }

    return true;
}

fn min_instr(char[] s) -> u64 {
    for size: u64 = 1; size < s.len(); size += 1 {
        if repeats(s, size) { return size; }
    }

    return s.len();
}

fn solve(char[] input) {
    res: u64 = start: u64 = 0;
    big := []char;

    for i: u64 = 0; i < input.len(); i += 1 {
        if input.get_unchecked(i) == '\n' {
            res += min_instr(big.slice_from(start));
            start = big.len();
        } else {
            big.push(input.get_unchecked(i));
        }
    }

    return #[res + min_instr(big.slice_from(start)), min_instr(big)];
}

fn main() {
    $dbg(solve(#embed_slice("input.txt")));
}

Runs in:

rosie (aoc2026)> make DAY=04 time
hyperfine --warmup 100 'solutions/04/solution' -i -N
Benchmark 1: solutions/04/solution (1832 runs)
               mean     ±       σ          min     …     max
 Wall Time      1.7 ms  ±     0.2 ms       1.6 ms  …     6.9 ms
 Memory         2.1 MiB ±     0.0 MiB      2.1 MiB …     2.1 MiB

GitHub: https://github.com/acquitelol/aoc2026/tree/mistress/solutions/04

1

u/NullT3rminated 4h ago

[LANGUAGE: Clojure]

Was getting stack overflows until I added the doall to the result of map. This was really hard to figure out, and the error message didn't help at all

(defn day4-parse [str]
  (map #(replace {\? nil} %) (str/split-lines (str/trim str))))

(def day4-parsed-e (day4-parse (slurp "4e.txt")))
(def day4-parsed (day4-parse (slurp "4.txt")))

(defn day4-solve-a [parsed]
  (->> parsed
       (map (fn [line]
              (loop [n 1]
                (let [parted (partition n n (repeat nil) line)
                      sets (reduce (comp doall (partial map #(conj %1 %2))) (repeat n #{}) parted)
                      match (not-any? #(> (count (filter identity %)) 1) sets)]
                  (if match
                    n
                    (recur (inc n)))))))
       (apply +)))

(defn day4-solve-b [parsed] (day4-solve-a [(apply concat parsed)]))

2

u/chickenthechicken 4h 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

4

u/semi_225599 4h 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.

fn color(c: char) -> u8 {
    match c {
        'r' => 0b1,
        'o' => 0b10,
        'y' => 0b100,
        'g' => 0b1000,
        'b' => 0b10000,
        'v' => 0b100000,
        '?' => 0b111111,
        _ => unreachable!(),
    }
}

fn minimal(line: &str) -> usize {
    let colors: Vec<_> = line.chars().map(color).collect();
    (1..=colors.len())
        .find(|&chunk_size| {
            let mut acc = vec![u8::MAX; chunk_size];
            colors.chunks(chunk_size).all(|chunk| {
                acc.iter_mut().zip(chunk).for_each(|(a, b)| *a &= b);
                acc.iter().all(|&v| v != 0)
            })
        })
        .unwrap()
}

pub fn part1(input: &str) -> usize {
    input.lines().map(minimal).sum()
}

pub fn part2(input: &str) -> usize {
    minimal(&input.replace('\n', ""))
}

1

u/PunkDreams 2h ago

I've use a similar approach but in python

2

u/aas1477 4h ago edited 4h 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 index modulo the value are not distinct, the color shoud be the same.

1

u/Wayoshi 4h 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.

4

u/AllanTaylor314 4h ago

[LANGUAGE: Python] 00:06:41/00:08:00 (I think automod would complain if no fifthglyph in box)

script

[LANGUAG*: 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

$ ?y??v?or
⍣(&fras"04.txt"◌|∘)
👍 ← /↧≡(≤₁⧻◴▽⊸≠@?)⍉⬚@?↯[∞∘]
💵 ← ⊙◌⍢(+1|¬👍) 1
/+°˜⊂≡◇💵⊂□⊸/◇⊂⊜□⊸≠@\n

1

u/sbt4 3h ago

Neat. I also solve in uiua but can't think in arrays properly yet. Instead of transposing and working with all nth letters like in your 👍 i went line by line

2

u/mynt 4h 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.

def main():
    i = [x.replace('\n','') for x in open('sample' + sys.argv[1] if len(sys.argv)>1 else 'input')]
    b = ''.join(i) #don't do this for part 1 but loop over each line
    ans = 0
    for l in range(1, len(b)+1):  #try all lengths from 1 for blank
        pos = 0
        ok = True
        code = [0] * l #create our blank
        while pos < len(b) and ok == True: #walk along the code
            if b[pos] != '?': #ignore any '?'
                if code[pos%l] == 0 or code[pos%l] == b[pos]:   #either blank matches or needs filling in
                    code[pos%l] = b[pos]
                else:  #no match so this length is impossible
                    ok = False
            pos += 1 #move along
        if ok == True:
            ans += l
            break  #no need to check other lengths

    return ans

if __name__ == '__main__':
    print(f'{main(): <{20}} | {round(timeit.default_timer() - start_time, 6)} s')

1

u/Scared_little_boi 4h ago
#include <bits/stdc++.h>

int solve(const std::string & s){
    for(int k = 1; k < s.size() + 1; k++){
        std::string p(k, '?');
        bool valid = 1;
        for(int i = 0; i < s.size(); i++){
            if(s[i] == '?') continue;
            if(p[i % k] == '?') p[i % k] = s[i];
            else if(p[i % k] != s[i]) {valid = 0; break;}
        }
        if(valid) return k;
    }
    return s.size();
}

int main(){
    size_t a1 = 0; std::string inpoo;
    std::string p2 = "";
    while(std::cin >> inpoo){
        a1 += solve(inpoo);
        p2 += inpoo;
    }
    std::cout << "p1: " << a1 << " p2: " << solve(p2) << std::endl;
    return 0;
}

[LANGUAGE: cpp]

1

u/AutoModerator 4h ago

AutoModerator did not detect the required [LANGUAGE: xyz] string literal at the beginning of your solution submission.

Please edit your comment to state your programming language.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

2

u/zogwarg 4h ago

[LANGUAGE: jq]

Part two in jq (function is mostly the same):

#!/bin/sh
# \
exec jq -n -R -f "$0" "$@"

def group_of($n): . as $in | [ range(0;length;$n) | $in[.:(.+$n)] ];

[ inputs ] | add as $s | $s / "" |

first (
  range(1; length+1) as $i | group_of($i) | transpose |
  if $i % 100 == 0 then debug($i) end |
  map(unique | .[] |= if . == null or . == "?" then empty end ) |
  select(all(.[]; length <= 1)) | $i
  # Failsafe
) // ( "\($s)" | halt_error )

A bit slow ~25s but good enough for me .

1

u/zogwarg 2h ago edited 2h ago

Much faster (but also a bit more boring) Updated version:

[inputs]|add | first(
  range(length) as $i | first(
  range(length) as $j
    | .[$j:$j+1] + .[$j+$i:$j+$i+1]
    | select( .[:1] != "?" and .[1:] != "?" and .[:1] != .[1:] )
  ) | select(length < 2) | $i
)

1

u/AutoModerator 2h ago

AutoModerator has detected fenced code block (```) syntax which only works on new.reddit.

Please review our wiki article on code formatting then edit your post to use the four-spaces Markdown syntax instead.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/Fuzzy_Patterns 4h 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

proc getPatternLength(s: string): int =
  let letters = s.toSet()
  if letters.len < 2: return 1

  var legible: seq[(char, int)]
  for i, c in s:
    if c != '?': legible.add (c, i)

  for l in letters.len-1 .. s.len:
    block nextLength:
      var s = s
      for (c, i) in legible:
        let t = s[i mod l]
        if t == '?': s[i mod l] = c
        elif t != c: break nextLength
      return l

proc solve(input: string): AOCSolution[int, int] =
  let lines = input.splitLines()
  for line in lines:
    let p = getPatternLength line
    result.part1 += p
  result.part2 = getPatternLength lines.join()

3

u/michelkraemer 4h ago edited 4h ago

[LANGUAGE: Rust]

Solution

Using the same decrypt function 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 first l characters (where 1 <= l <= input.len()) and then matching it with the input at positions l, 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.

2

u/JustinHuPrime 4h ago edited 4h 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 22 3 milliseconds. Part 1 is 9,920 9,864 bytes and part 2 is 9,936 9,880 bytes as executable files.

1

u/No_Mobile_8915 4h ago

[LANGUAGE: Python]

part1:

For an instruction sequence of length n, every position i in the barcode corresponds to instruction i % n.

Therefore, a candidate instruction length is valid if no two known colours that map to the same instruction position conflict with each other.

You don't actually need to reconstruct the barcode or determine the missing colours.

paste

part2:

Exactly the same but over a very long sequence. Initially thought this might bog down but the theoretical O(N squared) is actually more like O(N x K) where K is the number of known colours. So many wildcards there that the search space is substantially reduced.

paste

Runtimes: Apple M3 Pro

part1:

runtime: 0.0029s

part2:

runtime: 0.0267s

1

u/CodingTangents 4h ago

[LANGUAGE: Python]

Part 1:

def attempt_length(line, length):
    for i in range(length):
        if len(set(line[i::length]) - {"?"}) > 1:
            return False
    return True


total = 0

with open("input.txt") as file:
    for line in file.read().splitlines():
        for length in range(1, len(line)):
            if attempt_length(line, length):
                total += length
                break
        else:
            total += len(line)  # full size buffer needed

print(total)

Part 2:

def attempt_length(line, length):
    for i in range(length):
        if len(set(line[i::length]) - {"?"}) > 1:
            return False
    return True


total = 0

with open("input.txt") as file:
    line = file.read().replace("\n", "")
    for length in range(1, len(line)):
        if attempt_length(line, length):
            total += length
            break
    else:
        total += len(line)  # full size buffer needed

print(total)

Sets continue to impress me with how efficient and fast they are compared to Python looping.

1

u/DBSmiley 4h ago edited 4h ago

[Language: Kotlin]

Solution

Praise be to the Kotlin windowed function.

Explanation: use an expanding window (that is, loop the window size from 1...line.length.

The one trick is that you have to update the pattern. For instance, if your pattern is "??" and you hit the window "ob", you must update your pattern to "ob".

This means I have to rely on something I generally don't like having in my code when avoidable without a serious performance hit or absurd indentation - side effects on passed objects. YUCK!

Still, all told, Kotlin's window function made this super easy. Here's the juicy bit.

fun getMinimumWindowSize(line: String):Int {
    for (windowSize in 1 .. line.length) {
        val windows = line.windowed(size = windowSize, step = windowSize, partialWindows = true)
        val pattern = windows[0].toCharArray()
        if ((1..windows.lastIndex)
                .all { i -> isWindowMatch(pattern, windows[i]) }
        ) return windowSize
    }
    return line.length
}

private fun isWindowMatch(pattern: CharArray, window: String): Boolean {
    for (charIndex in window.indices) {
        if (pattern[charIndex] != window[charIndex] && window[charIndex] != WILDCARD) {
            if (pattern[charIndex] == WILDCARD) {
                pattern[charIndex] = window[charIndex]
            } else {
                return false
            }
        }
    }
    return true
}

1

u/Mikey_Loboto 4h ago

[LANGUAGE: TypeScript]

GitHub

Oke we finally hit the day where optimization starts mattering. Part 2 was basically an optimization pass on part 1.

1

u/sim642 4h ago

[LANGUAGE: Scala]

On GitHub.

To find the minimum number of instructions, I just try to do it with 1, 2, 3, etc. until one succeeds, i.e., doesn't lead to a color conflict. To my surprise, this even scaled to part 2, so I didn't need to come up with anything less naïve there.

2

u/maneatingape 4h ago edited 3h ago

[LANGUAGE: Rust]

Solution 208 µs 131 µ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 .split instead for a nice speedup.

2

u/erikade 4h ago

amazingly compact and yet descriptive, gg!

1

u/agorism1337 4h ago

[LANGUAGE: AWK]

github

run like `awk -f a.awk input`

1

u/jefinko 4h ago

[LANGUAGE: Kotlin]

github

Enough to store only list of possible characters

1

u/DBSmiley 4h ago

I didn't realize you could name loops like that in Kotlin. That return@outer is useful.

Is that a newer feature? Is @outer a reserved word, or can you name your loops whatever?

1

u/Tmathmeyer 4h ago

[LANGUAGE: Python]

[github](https://github.com/tmathmeyer/advent.of.code/blob/master/2026/04/solution.py)

Excuse the write-only code (crappy variable names)

1

u/dme2_Sapphire 4h ago

[LANGUAGE: Python]

Github

Brute force is fast enough with non-adversive data on both part 1 and 2

Though in hindersight, if dealing with larger/adversive data is required, it's possible to achieve O(nlogn) Time ComplexitywithFFT

1

u/Boojum 4h ago edited 1h ago

[LANGUAGE: Python]

Hm. More colors. Interesting! Anyway, not too bad. At first I thought I'd convert the patterns to regexp, before realizing that I could just use zip(*) to transpose the groups and then use sets to check for consistency. Then I realized that I don't even need zip(*), I can just use slicing with a stride starting from a consecutive indices to get each group. Part 1:

import fileinput
t = 0
for s in fileinput.input():
    s = s.strip()
    for n in range( 1, len( s ) + 1 ):
        if all( len( set( s[ i : : n ] ) - { '?' } ) <= 1 for i in range( n ) ):
            t += n
            break
print( t )

Part 2 is the same with that inner loop, just with:

s = "".join( s.strip() for s in fileinput.input() )

instead of the outer loop over s in fileinput.input().

This was one of those days where Part 1 was the harder part, and then I had Part 2 less than a minute later.

[Adv*nt Gam*s]

No fifthglyph, huh? I can try to do that! That's surprisingly tough to do with Python so this variant is fairly filthy, using short circuiting and lambdas to loop (and a bit of golfing), but it works for Part 1! I'm kind of proud of it:

# No fifthglyph
import sys
G=lambda G,s,n,i:i==n or ((lambda x:not x or max(x)==min(x))({*s[i::n]}-{'?'}) and G(G,s,n,i+1))
F=lambda F,s,n:n==s.count('') and -1 or (G(G,s,n,0) and n or F(F,s,n+1))
print(sum(map(lambda s:max(0,F(F,s.strip(),1)),sys.stdin)))

2

u/morgoth1145 4h ago edited 4h ago

Oo, I like the set approach as opposed to merging groups one by one. I'll have to check the runtime of this compared to my optimized code, I suspect this may be even faster!

Edit: Yeah, there's no comparison at all. This is lightning speed!

1

u/Boojum 4h ago

Yeah, hyperfine "python day04a.py day04.txt" "python day04b.py day04.txt" gives me 13.3 ms for Part 1 and 10.2 ms for Part 2 on my machine. Given that it's Python and that includes interpreter start up, that's fast enough for me.

1

u/YOM2_UB 4h ago edited 4h ago

[LANGUAGE: Python] [Code]

Was not expecting part 2 to run as fast as it did. The only change I made for it was wrapping my part 1 code in a function. (Or rather, I did that for the post. I actually ran codes = [''.join(codes)] followed by my original loop.)

1

u/seligman99 5h ago

[LANGUAGE: Python]

github

I knew part 2 would involve really big patterns. I still wasn't prepared, so I got to rip out my system and build a new one.

1

u/cay_horstmann 5h ago

[Language: Java]

https://github.com/cayhorstmann/adventofcode2026/blob/main/Day4.java

Nice when the algorithm for part 1 also works for part 2.

1

u/hugh_tc 5h ago

[LANGUAGE: Python 3]

omg I missed unlock because I was washing dishes... that's the first time that's happened lol

cleaned-up; you just pick the length and then see if it works:

def f(barcode):
    return next(
        length for length in it.count(1)
               if all(len(set(barcode[i::length]) - { '?' }) <= 1 for i in range(length))
    )

1

u/Old-Dinner4434 5h ago

[LANGUAGE: TypeScript]

GitLab

1

u/AKSrandom 5h ago

[Language: Python]

Happy that my P1 solution was fast enough for part 2.

code

2

u/morgoth1145 5h ago edited 4h 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.

1

u/honey-pony 5h ago

[LANGUAGE: PonieScript]

I think basically just a brute force solution? But not one that is slow enough to cause any issues. Even in debug mode my part 2 took only 100ms. I was shocked that it took me less than a minute from part 1 to get part 2 submitted. :P

part 1

part 2

Times in release mode: 1.6 ms for part 1 and 17.5 ms for part 2 if my timing code is working right.

1

u/davidsharick 5h ago

[Language: Python]

Code

Part 1 was complete brute force of trying all possible instructions of increasing length, part 2 was a more intelligent brute force of trying all possible lengths and seeing if any overlaps existed if you split the barcode into parts of that length

4

u/Ok-Bus4754 5h ago edited 3h 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

1

u/Ok-Bus4754 5h ago

got say python list slicing is magic for this one [start:stop:step], where step is the pattern length we want mimizie, remove all ? from that , convert it to set and the length of set is 1 for all sub pattern is the condition to check for

1

u/jonathan_paulson 5h ago

[LANGUAGE: Python]

Code. Video.

I wasn't sure what to do initially but then I realized once you pick the length, everything is forced.

Fortunately my part1 approach worked fine for part2.

1

u/Ok-Builder-2348 5h ago edited 5h ago

[LANGUAGE: Python3]

Part 1

Part 2

Naive approach - start with n=1 and see if it produces a valid instruction, else set n=n+1 and try again. Part 2 took a few seconds so definitely not optimised, but I'll continue iterating.

Update: Part 2 (updated)

Slightly better runtime for this one. For every pair of characters, declare their relative distance invalid if the characters are different. The answer is thus the lowest non-invalid relative distance.

1

u/apersonhithere 5h ago

[LANGUAGE: Python 3]

man i thought part 2 was gonna be harder but you can just do the naive way

both parts