For this year's Advent of Code I've decided to use my two current favourite languages: Roc andRaku. Each day links to the full write-up on the blog, gives both programs one after the other, and states the answer at the end.

Day 1 - The three most common IDs

Full solution →

# Day 1: Roc
input =
	\\232
	\\351
	\\...

tally = |counts, id| {
	match Dict.get(counts, id) {
		Ok(n) => Dict.insert(counts, id, n + 1)
		Err(_) => Dict.insert(counts, id, 1.U64)
	}
}

main! = |_| {
	ids =
		Str.split_on(input, "\n")
			|> List.keep_oks(|line| U64.from_str(line))

	counts = List.fold(ids, Dict.empty(), tally)

	top3 =
		Dict.to_list(counts)
			|> List.sort_by_reversed(|entry| entry.1)
			|> List.take_first(3)

	product = List.fold(top3, 1, |acc, entry| acc * entry.0)

	Echo.line!("top3: ${Str.inspect(top3)}\n")
	Echo.line!("answer: ${product.to_str()}\n")
	Ok({})
}
# Day 1: Raku
my $path = @*ARGS[0] // '../data/day1.txt';
my @ids = $path.IO.lines.map(*.Int);

my @top = @ids
    .Bag
    .sort(-*.value)
    .head(3)
    .map(*.key);

say @top.join(", ");
say @top.reduce({ $^a * $^b });

Solution: 164978112

Day 2 - The robot's total distance

Full solution →

# Day 2: Roc
input = "gvvggogbvogbbrrvgvrb...orgborvbgvvroggbrrrr"

idx : U8 -> U64
idx = |b| {
    match b {
        114 => 0
        111 => 1
        121 => 2
        103 => 3
        98 => 4
        118 => 5
        _ => 0
    }
}

main! = |_| {
    bytes = Str.to_utf8(input)
    final = List.fold(bytes, { pos: 0, total: 0 }, |state, b| {
        target = idx(b)
        raw = (target + 6 - state.pos) % 6
        dist = if raw == 0 { 6 } else { raw }
        { pos: target, total: state.total + dist }
    })
    Echo.line!("answer: ${final.total.to_str()}\n")
    Ok({})
}
# Day 2: Raku
my $path = @*ARGS[0] // '../data/day2.txt';
my $program = $path.IO.slurp.trim;

my @cycle = <r o y g b v>;
my ($pos, $total) = (0, 0);

for $program.comb -> $color {
    my $target = @cycle.first(* eq $color, :k);
    my $d = ($target - $pos) % 6 || 6;
    $total += $d;
    $pos = $target;
}

say $total;

Solution: 3756

Part two

# Day 2: Roc (part two)
input = "gvvggogbvogbbrrvgvrb...orgborvbgvvroggbrrrr"

idx : U8 -> U64
idx = |b| {
    match b {
        114 => 0
        111 => 1
        121 => 2
        103 => 3
        98 => 4
        118 => 5
        _ => 0
    }
}

go = |left, pos, total| {
    if Dict.is_empty(left) {
        total
    } else {
        choice = List.fold(Dict.to_list(left), { colour: 0, dist: 0 }, |best, entry| {
            colour = entry.0
            raw = (colour + 6 - pos) % 6
            dist = if raw == 0 { 6 } else { raw }
            if dist > best.dist { { colour: colour, dist: dist } } else { best }
        })
        next = match Dict.get(left, choice.colour) {
            Ok(1) => Dict.remove(left, choice.colour)
            Ok(n) => Dict.insert(left, choice.colour, n - 1)
            Err(_) => left
        }
        go(next, choice.colour, total + choice.dist)
    }
}

main! = |_| {
    counts = List.fold(Str.to_utf8(input), Dict.empty(), |left, b| {
        match Dict.get(left, idx(b)) {
            Ok(n) => Dict.insert(left, idx(b), n + 1)
            Err(_) => Dict.insert(left, idx(b), 1.U64)
        }
    })
    Echo.line!("answer: ${go(counts, 0, 0).to_str()}\n")
    Ok({})
}
# Day 2: Raku (part two)
my $path = @*ARGS[0] // '../data/day2.txt';
my %left = $path.IO.slurp.trim.comb.Bag;

my @cycle = <r o y g b v>;
my ($pos, $total) = (0, 0);

while %left.elems {
    my $c = %left.keys.max({ (@cycle.first(* eq $_, :k) - $pos) % 6 || 6 });
    my $d = (@cycle.first(* eq $c, :k) - $pos) % 6 || 6;
    $total += $d;
    $pos = @cycle.first(* eq $c, :k);
    %left{$c}--;
    %left{$c}:delete if %left{$c} == 0;
}

say $total;

Solution: 6247

Day 3 - The squares planted in the forest

Full solution →

# Day 3: Roc
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({})
}
# Day 3: Raku
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;

Solution: 405

Part two

# Day 3: Roc (part two)
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) ?? [])

    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)

    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({})
}
# Day 3: Raku (part two)
my $path = @*ARGS[0] // '../data/day3.txt';

my @rows = $path.IO.lines;
my ($h, $w) = (@rows.elems, @rows[0].chars);

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);
}

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;

Solution: 2433

Day 4 - The shortest list of instructions

Full solution →

# Day 4: Roc
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({})
}
# Day 4: Raku
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;

Solution: 8132

Part two

# Day 4: Roc (part two)
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({})
}
# Day 4: Raku (part two)
# 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;

Solution: 1642