Skip to content

Instantly share code, notes, and snippets.

@citizen428
Last active December 7, 2020 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save citizen428/260a27e3ef25c483693edf7433777bd0 to your computer and use it in GitHub Desktop.
Save citizen428/260a27e3ef25c483693edf7433777bd0 to your computer and use it in GitHub Desktop.
AOC 2020 Raku
my @l = 'aoc-expenses.txt'.IO.lines;
# part 1
say [*] @l.combinations(2).first: *.sum == 2020;
# part 2
say [*] @l.combinations(3).first: *.sum == 2020;
my @pw = 'aoc-pw.txt'.IO.lines.map: *.split([' ', '-', ': ']);
sub count(@seq, $filter) { (@seq.grep: $filter).elems }
# part 1
count(@pw, {$_[0] <= $_[3].indices($_[2]).elems <= $_[1]}).say;
# part 2
count(@pw, {
my @chars = $_[3].comb;
so (@chars[$_[0]-1] ^ @chars[$_[1]-1]) eq $_[2]
}).say;
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($_) });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment