Skip to content

Instantly share code, notes, and snippets.

@mscha
Last active December 10, 2024 12:16
Show Gist options
  • Save mscha/eef02b21a294b554e88d7aa685781d13 to your computer and use it in GitHub Desktop.
Save mscha/eef02b21a294b554e88d7aa685781d13 to your computer and use it in GitHub Desktop.
Advent of Code 2024 day 10
#!/usr/bin/env raku
use v6.d;
$*OUT.out-buffer = False; # Autoflush
# Advent of Code 2024 day 10 -- https://adventofcode.com/2024/day/10
enum Direction <north east south west>;
class Position
{
has Int $.x;
has Int $.y;
my Int %dx{Direction} = north, 0, east,1, south,0, west,-1;
my Int %dy{Direction} = north,-1, east,0, south,1, west, 0;
method step(Direction $d) { pos($!x+%dx{$d}, $!y+%dy{$d}) }
method neighbours { Direction::.values.map({ self.step($_) }) }
method Str { "($!x,$!y)" }
method gist { self.Str }
method WHICH { ValueObjAt.new("Position|$!x|$!y") }
}
multi sub pos(Int() $x, Int() $y) { Position.new(:$x, :$y) }
multi sub pos(@xy) { pos(@xy[0], @xy[1]) }
class TopographicMap
{
has @.grid;
has $!height = @!grid.elems;
has $!width = @!grid[0].elems;
method height($pos) { @!grid[$pos.y;$pos.x] }
method trailheads
{
return (^$!width X ^$!height).map(*.&pos).grep({ self.height($_) == 0 });
}
method neighbours($pos)
{
return $pos.neighbours.grep({ .x ~~ ^$!width && .y ~~ ^$!height });
}
method neighbours-at-height($pos, $height)
{
return self.neighbours($pos).grep({ self.height($_) == $height });
}
method trailhead-score($pos, :$distinct = False)
{
return 0 unless self.height($pos) == 0;
my @hpos = $pos;
for 1..9 -> $h {
@hpos .= map({ slip self.neighbours-at-height($_, $h) });
@hpos .= unique unless $distinct;
}
return @hpos.elems;
}
method total-trailhead-score(:$distinct = False)
{
return self.trailheads.map({ self.trailhead-score($_, :$distinct) }).sum;
}
}
sub MAIN(IO() $inputfile where *.f = 'aoc10.input')
{
my $map = TopographicMap.new(:grid($inputfile.lines».comb));
say "Part 1: ", $map.total-trailhead-score;
say "Part 2: ", $map.total-trailhead-score(:distinct);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment