Advent of Code 2020 Day 3/25 in the Raku programming language

In Day 3, we have to walk through the forest that is mapped in the following way:

..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#

This pattern is repeated horizontally as many times as needed. In a single step, we can make three moves cells and one row down. It is also OK to pass through the trees, but you need to count them. As soon as you reached the bottom end of the forest, tell how many trees you encountered.

my @trees = 'forest.txt'.IO.lines.map: *.comb.Array;

my $height = @trees.elems;
my $width = @trees[0].elems;

my ($x, $y) = 0, 0;

my $trees = 0;
while $y < $height {
    $trees++ if @trees[$y][$x % $width] eq '#';

    $x += 3;
    $y++;
}

say $trees;

In my solution, I am building the @trees directly from the file by splitting the strings into characters: 'forest.txt'.IO.lines.map: *.comb.Array.

Then, a trivial loop with a clever piece: instead of copying the map, I am using the modulo operator to loop the second coordinate: @trees[$y][$x % $width]. The rest is obvious: if you see # at this position, increment the counter.

In the second part of the problem, the moves are different. Instead of ‘three to the right, one down’, the rules are different. You need to go through the forest a few times counting the trees on each pass, and then multiply the results. Here are the move rules for each pass:

  • Right 1, down 1.
  • Right 3, down 1.
  • Right 5, down 1.
  • Right 7, down 1.
  • Right 1, down 2.

Let us update the program a bit to reflect the new instructions. Notice how the for loop sets the array @step as a loop variable.

#!/usr/bin/env raku

my @trees = 'forest.txt'.IO.lines.map: *.comb.Array;

my $height = @trees.elems;
my $width = @trees[0].elems;

my $prod = 1;
for [[1, 1], [3, 1], [5, 1], [7, 1], [1, 2]] -> @step {
    my ($x, $y) = 0, 0;

    my $trees = 0;
    while $y < $height {
        $trees++ if @trees[$y][$x % $width] eq '#';

        $x += @step[0];
        $y += @step[1];
    }

    # say $trees;
    $prod *= $trees;
}

say $prod;

* * *

→ Browse the code on GitHub
→ See all blog posts on Advent of Code 2020

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code