Advent of Code Day 3 gives a map of a forest in which every cell holds a
tree (#) or ground (.), and asks how many grid-aligned squares have a
tree at all four corners. The corners have to be the same distance apart
in both directions, and no size is excluded, so a 2×2 block of trees
counts and so does a square whose corners are ninety cells apart. The
statement publishes ten small maps along with the counts they should
produce, which is enough to check a solution before the real map is
counted.
The puzzle input is published alongside this post as
/aoc/2026/data/day3.txt, a map of 141 rows
and 141 columns holding 1632 trees, with the statement’s worked example
in day3-example.txt. Complete
solutions are available as day3.roc and
day3.raku. The Raku snippet below is the
whole file; the Roc snippet is the whole file with the embedded input cut
down to three rows.
The map itself, scanned by the same algorithm the two solutions use:
The worked example from the problem statement, four small squares and one large:
#.#.#
.....
#.#.#
.....
#.#.#
Run against the published example file:
$ raku day3.raku ../data/day3-example.txt
5
The statement’s remaining nine maps, in the order it publishes them. Four contain one square:
#...# .#..# ..... #.###
..... ..... .##.. .##.#
..... ..... .##.. ##.##
..... .#..# ..... .#.#.
#...# .##.#
Four contain two:
#..# #...# #...#.. .##..
.##. ..... ....... .##.#
.##. ..#.# ..#...# .....
#..# ..... ....... #.##.
#.#.# #...#.. ..##.
.......
..#...#
And the last two contain five and thirty:
#.#.# #####
.....
#.#.# #####
.....
#.#.# #####
All ten, saved as ex01.txt to ex10.txt in that order and run through
the solution:
$ for f in ../data/ex*.txt; do raku day3.raku "$f"; done
1
1
1
1
2
2
2
2
5
30
Each count matches the statement. The algorithm behind them is three nested loops: try every cell as the top-left corner of a square, and for each tree there, try every side that still fits inside the map. 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 map is embedded in the source.
Day 1’s input was one value per line and day 2’s a single string. Day 3’s
is a grid, so each \\ line carries one whole row of it and
Str.split_on puts the rows back.
The complete solution, with the input cut down:
# The puzzle input: 141 rows of 141 cells, trees as '#'.
input =
\\...............................................................
\\#.............................................#.....#............
\\.#.......................#.#..............##.....#..#............
main! = |_| {
rows = List.map(Str.split_on(input, "\n"), |row| Str.to_utf8(row))
height = List.len(rows)
width = List.len(List.first(rows) ?? [])
var $count = 0.U64
for r in 0..<height {
top = List.get(rows, r) ?? []
for c in 0..<width {
if (List.get(top, c) ?? 46) == 35 {
var $s = 1.U64
while r + $s < height and c + $s < width {
bottom = List.get(rows, r + $s) ?? []
if (List.get(top, c + $s) ?? 46) == 35 and
(List.get(bottom, c) ?? 46) == 35 and
(List.get(bottom, c + $s) ?? 46) == 35 {
$count = $count + 1
}
$s = $s + 1
}
}
}
}
Echo.line!("answer: ${$count.to_str()}\n")
Ok({})
}
The downloadable file carries all 141 rows at their full width of 141 characters. Run against the real map:
$ roc run day3.roc
answer: 405
1.1Str.len answers a question instead of a number
Rows are split into bytes before anything else happens, because strings
in Roc 0.1.0 are not where you look things up. Str.graphemes does not
exist:
Str.graphemes does not exist.
h = Str.graphemes("ab")
^^^^^^^^^^^^^^^^^^^^
Str is in scope, but it has no associated graphemes.
Str.len does exist, and calling it does not fail. It returns a tag
whose payload explains the problem:
LearnAboutStringsInRoc("String length depends on what you count: UTF-8
bytes, Unicode code points, or grapheme clusters ... Use
Str.count_utf8_bytes for the byte count, or Str.is_empty to check whether
a string is empty.")
The compiler is right that the question is ambiguous, and equally unhelp
ful when the answer is needed now, so the rows go through Str.to_utf8
and become List(U8). From there a cell is a U8 and the test for a
tree is == 35, with 46 standing in for ground when a lookup falls off
the map.
1.2Every corner check carries a default
List.get does not return the element. Its type is
List(item), U64 -> Try(item, [OutOfBounds]), so each of the three
corner tests has to answer for the failure case as well:
if (List.get(top, c + $s) ?? 46) == 35 and
(List.get(bottom, c) ?? 46) == 35 and
(List.get(bottom, c + $s) ?? 46) == 35 {
?? takes the value on the right when the left side is an Err, which
is the same match on Ok and Err that day 1 wrote out by hand,
compressed into an operator. The program makes 78,251 of these
three-corner checks, and the default is never the answer in any of them:
while r + $s < height and c + $s < width has already ruled the edge
out. It is written down anyway, because the type asks.
1.3and instead of &&, True instead of true
The condition above is joined with and, which is a keyword in this
language. && is not an operator:
unexpected expression syntax
I was parsing an expression, and this token cannot start an expression
here.
both = true && false
^
I found & here.
The operands had the same problem. true and false are not in scope:
Nothing is named true in this scope.
x = if true { 1 } else { 2 }
^^^^
Is it misspelled, or is there an import missing?
Bool is the tag union [False, True], so the literals are True and
False, and conjunction and disjunction are the keywords and and or.
Both short-circuit, which matters here: the second and third corner are
not read when the first one is ground.
1.4A counter seeded at zero would print 405.0
Numeric literals are inferred, and nothing in $count = $count + 1
constrains a bare 0 to be an integer. Written without the suffix, the
program ends happily with:
count: 1.0
Day 1 met the same rule on a dictionary value and wrote 1.U64. The
counter is seeded 0.U64, which fixes its type before the first
iteration rather than after the last one.
1.5for, while and var
Days 1 and 2 were folds, because what they accumulated was a value that
each step produced. Here the state is a position and a count, and Roc
0.1.0 has ordinary loops for that: for r in 0..<height over the rows,
a second over the columns, and a while that advances the side length
until either edge of the map is reached. The language reference notes
that a loop over a range compiles to the same counter a hand-written C
loop would use, so nothing about this shape costs anything to express.
Reassignment is var plus a $-prefixed name, and the whole scan is 26
lines of it.
2Raku
The same puzzle in Raku is the whole file:
# usage: raku day3.raku [path/to/input] (default: ../data/day3.txt)
my $path = @*ARGS[0] // '../data/day3.txt';
my @grid = $path.IO.lines.map(*.comb.Array);
my ($h, $w) = (@grid.elems, @grid[0].elems);
my $count = 0;
for 0 ..^ $h -> $r {
for 0 ..^ $w -> $c {
next unless @grid[$r][$c] eq '#';
for 1 .. min($h - $r, $w - $c) - 1 -> $s {
$count++ if @grid[$r][$c + $s] eq '#'
&& @grid[$r + $s][$c] eq '#'
&& @grid[$r + $s][$c + $s] eq '#';
}
}
}
say $count;
$ raku day3.raku
405
$ raku day3.raku ../data/day3-example.txt
5
2.1A row is an array of characters
.comb splits a line into graphemes, and .Array turns each row into a
real array. Both forms index identically, so the suffix is about cost
rather than correctness: on the real map, three runs each, comb.Array
finished in 180 ms and plain comb in 195 ms, both printing 405. Row and
column counts come from .elems, which leaves $h and $w as ordinary
numbers that the loop bounds do the rest with.
2.2The side range that ends before it starts
The side loop is 1 .. min($h - $r, $w - $c) - 1, with no guard around
it. A tree on the last row or column makes min return 1, so the range
becomes 1 .. 0, and Raku iterates an inverted range zero times:
$ raku -e 'say (1 .. 0).elems'
0
The bounds are therefore complete as written, which is why there is no
equivalent of Roc’s three ?? defaults anywhere in this file.
2.3An index past the end returns (Any)
That completeness is a property of the loops, not of the indexing. Asked
for a cell beyond the end of a row, Raku returns (Any), warns about the
uninitialized value, and eq '#' is false:
$ raku -e 'my @a = <a b c>; say @a[5] eq "#"'
Use of uninitialized value @a[5] of type Any in string context.
False
So an off-by-one here loses a square quietly, exactly as Roc’s ?? 46
would. Neither version reads out of bounds in practice; both are written
so that the mistake, if it were made, would look like ground.
3The answer
Both languages agree:
$ raku day3.raku
405
$ roc run day3.roc
answer: 405
Two checks written for the occasion agreed as well: one pairs trees along the down-right diagonal and tests the other two corners instead of scanning from each top-left tree, and one stores every row as a 141-bit integer and intersects shifted masks. Both print 405, and all ten statement examples were reproduced by the Raku file before the real map was counted.
The 405 squares spread almost evenly across every side length up to 70:
sides 1-10: 55
sides 11-20: 65
sides 21-30: 60
sides 31-40: 64
sides 41-50: 57
sides 51-60: 50
sides 61-70: 51
sides 71-80: 2
sides 91-100: 1
The median square has its corners 35 cells apart, only two are the smallest possible, and the single largest has corners 91 cells apart, starting at row 6, column 3. For contrast, 100 maps with the same 1632 trees scattered uniformly over the same 141 × 141 cells averaged 42 squares, with the best reaching 59. This map has 405, which is what somewhat evenly spaced looks like from above.
On timings, the compiled Roc binary settles at 4 ms per run once the first, cold-cache run has paged it in (160 ms on the first, 280 ms to build with 0 errors and 0 warnings). Raku, including interpreter startup, takes 180 ms warm, against 96 ms for day 2’s 1042 instructions: the extra 84 ms is 78,251 three-corner checks and 1632 rows worth of character splitting, and neither number is about the language.
4Part two
Part two drops the assumption that made part one easy. The afforestation protocols do not require the trees to be planted square to the grid, so a square may sit at any rotation, and the count has to include those as well. The 405 axis-aligned squares are still squares; the question is what else the forest hides.
The statement’s part two examples, in the order it publishes them. Four maps contain one square:
#...# .#... ..#.. ....#..
..... ....# ..... .......
..... ..... #...# #......
..... #.... ..... .......
#...# ...#. ..#.. ......#
.......
..#....
Two contain six, four small squares, a medium one and a large one:
#..#..# ..#....
....... ....#..
....... .#....#
#..#..# ...#...
....... #....#.
....... ..#....
#..#..# ....#..
One contains five, and the full seven by seven grid contains 196:
#.### #######
.##.# #######
##.## #######
.#.#. #######
.##.# #######
#######
#######
Run in that order through the part two solution:
$ for f in ../data/p2ex*.txt; do raku day3-part2.raku "$f"; done
1
1
1
1
6
6
5
196
The same map with rotation allowed, scanned in two passes:
Every ordered pair of trees is a candidate edge: step from one tree to the next to get a vector, turn that vector a quarter circle, and require the other two corners to hold trees as well. The pairs are ordered, so each square is found four times, once for each of its edges, and the first version of both programs divided the total by four.
4.1The wedge rule
Roc could not keep that version. Its unsigned integers crash on
underflow, the released compiler has no U64 to I64 conversion to
borrow a signed type with (the current documentation lists
to_i64_wrap; 0.1.0 rejects it), and the edge vector points in all four
directions, so about half the pairs would subtract the larger row from
the smaller one. Day 2 met the same wall and added six before the
modulo; here the fix had to be structural.
The rewrite keeps only the ordered pair whose edge steps down and left-or-level:
if q.0 > p.0 and q.1 <= p.1 {
A square’s four edge vectors point in four directions ninety degrees
apart, and that wedge spans a quarter turn, so exactly one pair per
square survives and the division is no longer needed. What is left is
the quarter turn itself, (p.c - q.c, q.r - p.r), whose two components
are non-negative by the rule. Every coordinate in the inner loop is
therefore an addition:
dr = q.0 - p.0
ncd = p.1 - q.1
vr = p.0 + ncd
vc = p.1 + dr
br = q.0 + ncd
bc = q.1 + dr
The Raku file keeps the plainer form, with the division at the end:
# usage: raku day3-part2.raku [path/to/input] (default: ../data/day3.txt)
my $path = @*ARGS[0] // '../data/day3.txt';
my @rows = $path.IO.lines;
my ($h, $w) = (@rows.elems, @rows[0].chars);
# trees as parallel arrays, plus a boolean grid for membership
my (@tr, @tc);
my @is;
for @rows.kv -> $r, $row {
my @line;
for $row.comb.kv -> $c, $cell {
my $tree = $cell eq '#';
@line.push($tree);
if $tree { @tr.push($r); @tc.push($c); }
}
@is.push(@line);
}
# Every ordered pair of trees is a candidate edge: from a tree, step to a
# second tree to get the edge vector (dr, dc), turn it a quarter circle to
# (-dc, dr), and require the other two corners to be trees as well. Each
# square is found once per edge, four edges, hence the final division.
my $hits = 0;
my $n = @tr.elems;
for 0 ..^ $n -> $i {
my $r = @tr[$i];
my $c = @tc[$i];
for 0 ..^ $n -> $j {
my $dr = @tr[$j] - $r;
my $dc = @tc[$j] - $c;
next if $dr == 0 && $dc == 0;
my $br = $r + $dr - $dc;
my $bc = $c + $dc + $dr;
my $vr = $r - $dc;
my $vc = $c + $dr;
next unless 0 <= $br < $h && 0 <= $bc < $w
&& 0 <= $vr < $h && 0 <= $vc < $w;
next unless @is[$br][$bc] && @is[$vr][$vc];
$hits++;
}
}
say $hits div 4;
$ raku day3-part2.raku
2433
The complete Roc solution, with the input cut down:
# The puzzle input: 141 rows of 141 cells, trees as '#'.
input =
\\...............................................................
\\#.............................................#.....#............
\\.#.......................#.#..............##.....#..#............
main! = |_| {
rows = List.map(Str.split_on(input, "\n"), |row| Str.to_utf8(row))
height = List.len(rows)
width = List.len(List.first(rows) ?? [])
# trees as (row, column) pairs, plus a Dict of flattened positions
step_row = |st, row, r| {
List.fold_with_index(row, st, |acc, b, c| {
if b == 35 {
{
trees: List.append(acc.trees, (r, c)),
keys: Dict.insert(acc.keys, r * 1000 + c, {}),
}
} else {
acc
}
})
}
built = List.fold_with_index(rows, { trees: [], keys: Dict.empty() }, step_row)
# A square is found from one of its ordered edge pairs. Of a square's
# four, exactly one steps down and left-or-level (q.r > p.r, q.c <= p.c);
# the quarter turn (-dc, dr) is then non-negative componentwise, so every
# coordinate below is an addition and nothing can underflow.
hits = List.fold(built.trees, 0.U64, |acc, p| {
List.fold(built.trees, acc, |acc2, q| {
if q.0 > p.0 and q.1 <= p.1 {
dr = q.0 - p.0
ncd = p.1 - q.1
vr = p.0 + ncd
vc = p.1 + dr
br = q.0 + ncd
bc = q.1 + dr
fits = vr < height and vc < width and br < height and bc < width
if fits {
if Dict.contains(built.keys, vr * 1000 + vc) and Dict.contains(built.keys, br * 1000 + bc) {
acc2 + 1
} else {
acc2
}
} else {
acc2
}
} else {
acc2
}
})
})
Echo.line!("answer: ${hits.to_str()}\n")
Ok({})
}
$ roc run day3-part2.roc
answer: 2433
Four implementations agree on 2433: the two programs above, a check that keeps the minimum corner of each square instead of dividing, and one that treats pairs of trees as potential diagonals and turns them into the other two corners. All four reproduce the eight published examples as well.
Of the 2433 squares, 405 are the axis-aligned ones from part one. The other 2028 are rotated, with side lengths in 1024 distinct values from the square root of 2 up to about 120 cells, which is what fills the figure above.
On timings, the compiled Roc binary runs the 2.66 million candidate pairs in 18 ms (183 ms on the first run, 372 ms to build with 0 errors and 0 warnings). Raku takes 5.9 s, thirty-three times the 180 ms it needs for part one, because part two compares every tree with every other tree where part one made 78,251 three-corner checks.
5Neither language has a grid
Both programs are three loops over the same shape, and neither language has anywhere to put a two-dimensional map. Each builds one the same way, a list of rows with the dimensions held in two variables, and everything the puzzle calls the map is a convention the code has to keep to.
The difference appears when an index stops keeping to it. Roc’s
List.get returns a Try, so every corner test answers the failure case
as well as the real one, in 78,251 checks. The default is the byte for
ground, which means an index one row past the bottom would read as an
empty cell and lose a square without a word. The while condition rules
that out before the lookup runs, and the source still says what would
happen if it did not.
Raku has no equivalent clause. Ask it for a cell past the end and it
hands back (Any), warns, and compares false: the same silent answer,
written down nowhere. The safety in both versions lives in the loop
bounds, and Roc’s type records something about those bounds only
indirectly, by insisting that every lookup could fail and making the
program say what failure costs.
I preferred the version that says it. The three ?? 46 are the only part
of the Roc program with an opinion about the map’s shape, and they sit on
one screen next to the bounds that rule them out. In Raku the same fact is
spread across three loop headers, which is less to read and more to take
on trust, and for a program this size that trade is close enough to call
either way.
Part two then took the grid away. A candidate stops being a row, a column
and a side and becomes a pair of trees and a quarter turn, so the loop
bounds that guaranteed an in-range read describe nothing at all. Roc’s
answer was to change the question rather than add checks: the wedge rule
picks one ordered pair per square so that every coordinate after it is
known in advance to be an addition, which is the same instinct as day 2’s
+ 6 before the modulo, written out at a larger scale. Raku needed no
rewrite, because its subtraction already produces negative numbers and its
bounds are ordinary comparisons. The cost of that difference landed in the
clock instead: 5.9 seconds against Roc’s 18 milliseconds.
The cells moved too. Roc 0.1.0 has no Str.graphemes, and Str.len
answers a question instead of returning a number, so the map became bytes
before anything could be indexed and a tree is 35. Raku splits into
characters and a tree is '#'. One solution holds the forest as numbers
and the other as text, and neither of them holds it as a grid, because
that is the part the loops agree to.