Advent of Code Day 4 is a list of barcodes damaged by the weather at the North Pole pier. Each barcode is a run of six colours, red through violet, with a question mark wherever the colour cannot be read. The printer takes a list of instructions, repeats it until the barcode reaches the right length, cuts the last copy off, and charges per instruction rather than per character, so the question for each barcode is how short a list can still have printed it. A question mark accepts whatever the printer happens to produce there, which is what lets one instruction print a barcode of eight characters and forces five to print another of the same length.
The puzzle input is published alongside this post as
/aoc/2026/data/day4.txt: 4023 barcodes,
20000 characters in total, each barcode between two and eight
characters long, with the statement’s six examples in
day4-example.txt. Complete
solutions are available as day4.roc and
day4.raku. The Raku snippet below is the
whole file; the Roc snippet is the whole file with the embedded input,
all 4023 lines of it, cut down to three.
Every barcode in the list, reprinted by the same algorithm the two solutions use:
The six barcodes from the statement and the fewest instructions each one needs:
| barcode | instructions |
|---|---|
rgbrgbrgbr | 3 |
?rv | 2 |
o??v???y | 5 |
??bg?v?? | 4 |
??b????? | 1 |
??? | 1 |
| total | 16 |
Run through the solution one barcode at a time, and then as the file they arrive in:
$ for f in ex*.txt; do raku day4.raku "$f"; done
3
2
5
4
1
1
$ raku day4.raku ../data/day4-example.txt
16
Every count matches the statement. The algorithm behind them takes one sentence: for each barcode, try every instruction-list length from one up to the length of the barcode itself, and keep the first length at which every two readable colours landing in the same slot of the repeat agree. What this post is about is how the two languages require that to be written.
1Roc
The platform constraint from the day 1 post has
not changed: a bare .roc file runs against a bundled platform whose
only capability is Echo.line!, so the input is embedded in the source.
Day 1 carried one value per \\ line and
day 3 one row of the grid per \\ line. Day 4
carries one barcode per \\ line, which makes day4.roc a
4069-line file in which 4023 lines are data.
# Advent of Code, Day 4
#
# Find the fewest instructions whose repetition can print each barcode.
# A list of p instructions prints a barcode of length n exactly when every
# two known colours at positions congruent modulo p agree, so the answer
# is the smallest such p. It always exists: n instructions, one per
# position, print anything.
input =
\\bb?
\\g????g?
\\...
fewest = |line| {
n = List.len(line)
var $p = 1.U64
var $answer = n
while $p <= n {
var $clash = False
var $i = 0.U64
while $i < n {
a = List.get(line, $i) ?? 63
if a != 63 {
var $j = 0.U64
while $j < $i {
b = List.get(line, $j) ?? 63
if b != 63 and ($j % $p) == ($i % $p) and b != a {
$clash = True
}
$j = $j + 1
}
}
$i = $i + 1
}
if $clash {
$p = $p + 1
} else {
$answer = $p
break
}
}
$answer
}
main! = |_| {
lines = List.map(Str.split_on(input, "\n"), |row| Str.to_utf8(row))
total = List.fold(lines, 0.U64, |acc, line| acc + fewest(line))
Echo.line!("answer: ${total.to_str()}\n")
Ok({})
}
$ roc build day4.roc
0 errors and 0 warnings found in 101ms while successfully building:
day4bin
$ ./day4bin
answer: 8132
1.1The colours are never named
The code contains one byte that belongs to the puzzle: 63, the byte for
?. Day 2’s program opened with an idx function mapping every colour
to a number, because it had to add distances around the six-colour
cycle. This one only ever asks whether two bytes are equal and whether
a byte is a hole, so the six colours appear in the input and nowhere in
the program.
1.2An unread position is a hole
Every read goes through List.get and its ?? 63, and Roc insists on
the default. List.get answers a Try, and asking whether a Try
equals a number is a compile error rather than a runtime question:
$ roc build try-compare.roc
── ✗ type mismatch ──────────────────────────────── try-compare.roc:3:27
This number is being used where a non-number type is needed.
if List.get(xs, 0) != 63 {
^^
Other code expects this to have the type:
Try(U8, [OutOfBounds])
The default I supplied is 63, which is the same byte the barcode uses for a colour nobody could read, so a position the program cannot reach would be treated exactly as the puzzle treats a colour it cannot read. The bounds are correct and the default never fires, but if it ever did the cost would be a shorter answer rather than a crash.
1.3The loop carries the answer out
The outer loop runs while $p <= n and leaves through break the
moment a length holds, copying that length into $answer first.
$answer starts at n because the loop cannot fall through: n
instructions, one per position, print any barcode of length n, so the
last candidate always succeeds. That fact is what bounds the search in
both languages, and in Roc it is written down as the initial value
rather than assumed by the loop.
2Raku
The same puzzle in Raku is the whole file:
# usage: raku day4.raku [path/to/input] (default: ../data/day4.txt)
my $path = @*ARGS[0] // '../data/day4.txt';
my $total = 0;
for $path.IO.lines -> $line {
my @c = $line.comb;
my $n = @c.elems;
for 1 .. $n -> $p {
my %seen;
my $clash = False;
for 0 ..^ $n -> $i {
my $cell = @c[$i];
next if $cell eq '?';
my $r = $i % $p;
$clash = True if %seen{$r}:exists && %seen{$r} ne $cell;
%seen{$r} = $cell;
}
if !$clash {
$total += $p;
last;
}
}
}
say $total;
$ raku day4.raku
8132
$ raku day4.raku ../data/day4-example.txt
16
2.1A string is not a list of characters
My first version read each barcode with $line[$i], which is what you
would write in most languages. A Str in Raku is a list of one element,
so index 0 hands back the whole line and index 1 does not exist:
$ raku -e 'my $s = "abc";
say $s[0];
say $s[1];'
abc
Index out of range. Is: 1, should be in 0..0
in block <unit> at -e line 3
It failed on the first barcode of the first example, which is the best
outcome a wrong assumption can have. .comb splits the line into
characters first, and @c indexes the way the rest of the program
assumes.
2.2The hash has to admit what it has not read
Recording the first readable colour for each slot is one line,
%seen{$r} = $cell. Reading one back is where the trouble is: a slot
that has never been written holds Any, and ne compares it rather
than asking whether it is there:
$ raku -e 'my %seen;
say %seen{0} ne "r";'
Use of uninitialized value %seen{'0'} of type Any in string context.
Methods .^name, .raku, .gist, or .say can be used to stringify it to something meaningful.
True
in block <unit> at -e line 2
I wrote :exists before running anything, so no run was lost. Deleting
it from that one line totals 712 on the real input instead of 8132,
after 30,972 warnings: every barcode with a readable colour in it
clashes at its first colour in every slot, finds no length that works,
and is skipped without being counted. 712 is exactly the number of
barcodes with nothing readable in them. The example file answers 1
instead of 16, after 106 warnings.
3The answer
Both languages agree:
$ raku day4.raku
8132
$ roc run day4.roc
answer: 8132
Two checks written for the occasion agreed as well. One walks each slot and records the first readable colour it finds, which is the Raku program’s method. The other collects the distances between every pair of clashing colours: a length works exactly when it divides none of those distances, because two positions share a slot precisely when their distance is a multiple of the length. Both print 8132, and the six statement examples were reproduced by the Raku file before the real list was totalled.
The 8132 instructions spread like this:
1 instruction 2211 barcodes
2 617
3 624
4 244
5 196
6 75
7 39
8 17
More than half the list needs a single instruction, because every readable colour in those barcodes is the same colour. 712 barcodes are illegible from end to end and 113 have no question marks at all, with 3198 somewhere in between. 226 barcodes need as many instructions as they have characters, which is the point at which nothing shorter can be found. The mean barcode costs 2.02 instructions and the median costs one.
On timings, the compiled Roc binary runs all 4023 barcodes in 2 ms once the first, cold-cache run has paged it in (4 ms on that first run, 101 ms to build with 0 errors and 0 warnings). Raku takes 140 ms including interpreter startup, against 170 ms for day 3’s map and 90 ms for day 2’s program. The six-barcode example file costs 100 ms of that 140, so the whole list adds about 40 ms to starting the interpreter.
4Part two
Part two takes the document back. It was never a list of barcodes: it is one barcode with newlines in it, and the first step is to remove them. The statement’s document, all fourteen lines of it:
rro??
?g
?g???
??r?????
??g?
??
yy?v?o
???v
b?g??
?y??v?or
????r?o
??
?????
?r??v?r
Joining those lines leaves one barcode of seventy characters:
rro???g?g?????r???????g???yy?v?o???vb?g???y??v?or????r?o????????r??v?r
which the printer reproduces from sixteen instructions, such as
rrovbrgogryybvro:
$ raku day4-part2.raku ../data/day4-part2-example.txt
16
The solutions are published as
day4-part2.roc and
day4-part2.raku, with the
statement’s document in
day4-part2-example.txt.
Joined, the real document is one barcode of 20000 characters, 6695 of
them readable and 13305 holes. The question is the one part one asked,
at a scale part one never reached. The barcode, swept by every candidate
length until one of them gets to the end, then folded at the answer:
4.1Joining the lines
Raku does the whole first step in one expression: $path.IO.lines.join
reads the lines and puts them back together with nothing between them.
Roc splits its embedded input and joins it again,
Str.join_with(Str.split_on(input, "\n"), ""), because the input is a
multiline literal and the platform still has no file I/O. Then
Str.join_with answers a Str, and everything that indexes it is
written for lists:
$ roc build day4-part2.roc
── ✗ type mismatch ────────────────────────────── day4-part2.roc:4035:18
The first argument being passed to this function has the wrong type.
n = List.len(barcode)
^^^^^^^
This argument has the type:
Str
But the function needs the first argument to be:
List(_item)
The barcode goes through Str.to_utf8 first, the same conversion day
3’s map rows needed before anything could be looked up in them.
4.2Twenty-two million pairs
Part one’s Roc program compared every pair of readable positions in a barcode, which costs at most twenty-eight comparisons for an eight-character one. This barcode has 6695 readable positions, so the same test would be 22,407,985 pairs for every candidate length it tried. Roc therefore takes the dictionary Raku’s part one program was already using: one slot, one colour, and the first clash ends the scan. The outer loop still walks the candidate lengths from one upward, so both programs now run the same algorithm and stop at the same place.
The whole Raku file:
# usage: raku day4-part2.raku [path/to/input] (default: ../data/day4.txt)
my $path = @*ARGS[0] // '../data/day4.txt';
my @c = $path.IO.lines.join.comb;
my $n = @c.elems;
my $answer = $n;
for 1 .. $n -> $p {
my %slots;
my $clash = False;
for 0 ..^ $n -> $i {
my $cell = @c[$i];
next if $cell eq '?';
my $slot = $i % $p;
$clash = True if %slots{$slot}:exists && %slots{$slot} ne $cell;
%slots{$slot} = $cell;
last if $clash;
}
if !$clash {
$answer = $p;
last;
}
}
say $answer;
$ raku day4-part2.raku
1642
The complete Roc solution, with the input cut down:
# The puzzle input: 4023 lines of one barcode, as given.
input =
\\rro??
\\?g
\\...
fewest = |lines| {
barcode = Str.to_utf8(Str.join_with(lines, ""))
n = List.len(barcode)
var $p = 1.U64
var $answer = n
while $p <= n {
var $slots = Dict.empty()
var $clash = False
var $i = 0.U64
while $i < n {
colour = List.get(barcode, $i) ?? 63
if colour != 63 {
slot = $i % $p
match Dict.get($slots, slot) {
Ok(known) => {
if known != colour {
$clash = True
}
}
Err(_) => {
$slots = Dict.insert($slots, slot, colour)
}
}
}
if $clash {
break
}
$i = $i + 1
}
if $clash {
$p = $p + 1
} else {
$answer = $p
break
}
}
$answer
}
main! = |_| {
lines = Str.split_on(input, "\n")
Echo.line!("answer: ${fewest(lines).to_str()}\n")
Ok({})
}
$ roc run day4-part2.roc
answer: 1642
Both programs reproduce the statement’s example, and three checks agree on the real document: the two above, and one that marks every distance at which two different colours stand, then looks for a length that divides none of them.
Of the 20000 characters, 6695 are readable, so each of the 1642 slots holds about four readable positions that all have to agree. The answer is 2 × 821, and the list repeats 12.18 times across the barcode before the printer cuts the last copy off.
On timings, the compiled Roc binary prints the answer in 17 ms once warm (156 ms on the first run, 254 ms to build with 0 errors and 0 warnings). Raku takes 510 ms against the 146 ms part one needs, for one barcode of 20000 characters instead of 4023 short ones, and the two walk 1,378,450 positions between candidate lengths to get there.
5The three things that were not there
Both programs are the same three moves: skip the hole, compare the readable colours that share a slot, stop at the first length that works. A barcode is at most eight characters, so nothing about the work was worth discussing, and neither language’s speed shaped a decision. What shaped the decisions was what each language does with a value that is not there yet, and there were three of them.
Roc will not let you ask. List.get answers a Try, and the program
cannot compile until ?? 63 says what the failure case costs. The
value I gave it is the byte for ?, so a position the program cannot
read is treated the way the puzzle treats a colour nobody could read.
I did not arrange that correspondence; the default had to be some byte
and the wildcard was the only one with a defensible meaning.
Raku lets you ask and then complains. A hash slot that has never been
written holds Any, and ne is happy to compare it. The answer it
gives without :exists is not random either: 712, the barcodes with
nothing readable to clash against, reached while 30,972 warnings scroll
past. A wrong answer that lands on a count of the program’s own blind
spot is still a wrong answer, and the only thing standing between it
and the right one is a token I typed because I knew to type it.
The third absence was the bug I actually lost a run to. $line[$i]
looks like indexing and is not, because a Str is a list of one. It
crashed immediately, which is the polite version, and .comb replaced
it.
Part two changed the scale rather than the question, and the difference
between the two programs changed with it. At eight characters Roc’s
pairwise test was the shorter program; at twenty thousand it would be
twenty-two million pairs per candidate length, so Roc grew the
dictionary Raku had been using since part one and the two files now hold
the same algorithm. What did not converge is the input. Raku’s
$path.IO.lines.join is one expression; Roc splits its embedded input,
joins it again, and sends the result through Str.to_utf8 because
everything that indexes it is written for a list. Part one’s wall was an
unread value, part two’s is a type, and both arrive the moment the
program has to treat the barcode as something other than the shape it
was handed.
I would keep the Roc program. It is twice the length of the Raku one
and does more work per barcode, and neither of those things matters at
eight characters. What matters is that the meaning of an unread value
is written into the expression that reads it, and the program cannot be
built until somebody has written it down. Raku’s answer is a convention
instead: split with .comb before you index, ask :exists before you
compare. The first cost me a run and the second I had, and the program
is correct only while both hold.