2024 AoC Day 6 – Guard Gallivant

This is a solution to Advent of Code 2024 day 6, written in Raku.

https://adventofcode.com/2024/day/6

Part One

Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?

use Test;

sub day-six($input, $size) {
    my @g[$size;$size] = $input.lines>>.comb;

    sub find-start() {
        for ^$size -> $y {
            for ^$size -> $x {
                return ($x, $y) if @g[$y;$x] eq '^';
            }
        }
    }

    my ($x, $y) = find-start();
    my $dir = '^';
    my $seen = SetHash.new;

    loop {
        $seen.set("{$x},{$y}");
        given $dir {
            when '^' {
                last if $y == 0;
                $dir = '>' if @g[$y - 1;$x] eq '#';
            }
            when '>' {
                last if $x == $size - 1;
                $dir = 'v' if @g[$y;$x + 1] eq '#';
            }
            when 'v' {
                last if $y == $size - 1;
                $dir = '<' if @g[$y + 1;$x] eq '#';
            }
            when '<' {
                last if $x == 0;
                $dir = '^' if @g[$y;$x - 1] eq '#';
            }
        }

        given $dir {
            when '^' { $y -= 1; }
            when '>' { $x += 1; }
            when 'v' { $y += 1; }
            when '<' { $x -= 1; }
        }
    }

    +$seen.keys
}

is day-six('test-6.txt'.IO.slurp, 10), 41, 'example input';
say day-six('input-6.txt'.IO.slurp, 130);
ok 1 - example input
5305

Part Two

You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?

TODO.

raku