DEV Community

loading...

Discussion on: Advent of Code 2020 Solution Megathread - Day 3: Toboggan Trajectory

Collapse
citizen428 profile image
Michael Kohl

Raku, first time I used classes. Alas, the Perl syntax highlighter seems to have some problems with this and Raku isn't a supported syntax type.

class Slope {
  has $.right;
  has $.down;

  method new($right, $down) { self.bless(right => $right, down => $down) }
}

class Map {
  has $.grid;
  has $.height;
  has $.width;

  method from-file($fname) {
    my @grid = $fname.IO.lines.map: *.comb;
    self.new: grid => @grid, height => @grid.elems, width => @grid.first.elems;
  }

  method is-tree($x; $y) { $!grid[$y][$x % $!width] ~~ '#' }

  method count-trees($slope, $start-x = 0, $start-y = 0) {
    sub count-trees-rec($prev-x = $start-x, $prev-y = $start-y, $count = 0) {
      my $y = $prev-y + $slope.down;
      return $count if $y > $!height;

      my $x = $prev-x + $slope.right;
      count-trees-rec($x, $y, self.is-tree($x, $y) ?? $count + 1 !! $count)
    }
    count-trees-rec();
  }
}

my $map = Map.from-file('aoc-map.txt');

# part 1
$map.count-trees(Slope.new(3, 1)).say;

# part 2
my @slopes = ((1, 1), (3, 1), (5, 1), (7, 1), (1, 2)).map({ Slope.new(|$_) });
say [*] @slopes.map({ $map.count-trees($_) });
Enter fullscreen mode Exit fullscreen mode