Raku: Advent of Code 2020 - Day Three

Below is a Raku solution to the puzzle for Day Three in the 2020 Advent of Code. Commentary follows the code.

use v6.d;
my @input = 'input'.IO.lines;
my @map;

for @input -> $line {
my $geology = ($line.comb xx *).flat;
@map.push($geology);
}

sub detect_collisions (Int $sx, Int $sy) {
my $rval = 0;
loop (my ($x,$y)=($sx,$sy); $y < @map.elems; $x+=$sx, $y+=$sy) {
$rval++ if @map[$y][$x] eq '#';
}
return $rval
}

# Part One
say "Part One: {detect_collisions(3,1)}";

# Part Two
my @collision;
for 1,1, 3,1, 5,1, 7,1, 1,2 -> $x, $y {
@collision.push(detect_collisions($x, $y));
}
say "Part Two: " ~ [*] @collision;

Lazy lists and infinite sequences, the list repetition operator, and the * whatever placeholder are a few of the things Raku provides which made the repeating geology input in today's challenge fairly easy to deal with.

As you can see in the following example code, the 'xx' repetition operator and flat routine make it easy to create an infinite lazy list. The * whatever placeholder in this context indicates infinite.
my @a='123'.comb;
say @a xx 3;
say (@a xx 3).flat;
say (@a xx *).flat;
([1 2 3] [1 2 3] [1 2 3])
(1 2 3 1 2 3 1 2 3)
(...) 

The rest of the code is fairly straightforward. The detect_collisions routine takes the slope for x and y and does the light work of counting # collisions. At the very end when printing out the answer for Part Two, I use a [*] reduction metaoperator to get the product of all collision counts.

One lesson I learned today was to use comb instead of split to convert a string into a sequence of individual characters. To my surprise in Raku given an empty string delimiter, split matches the empty string at the beginning and end of the string contents... returning an extra list item at the beginning and end. comb with an empty delimiter returns a sequence of the characters in the string. While at first blush the behavior of split is a surprise, it does make sense. And is probably an example of how the design of Raku focuses on maximizing consistency while minimizing idiosyncrasies and special cases.

Comments

Popular posts from this blog

Raku: Setting up Raku (for Contributors)

Raku: Advent of Code 2020 - Day Twelve

Raku: Advent of Code 2020 - Day Thirteen