/ domm

I hack Perl for fun and profit

Follow me on twitter!
Atom Icom ... on Atom!
<<<<<<<<<<
04.12.2020: Advent of Code Day 3 - the first modulo

Part 1

.. and the first 2D map!

Which is quite simple to parse in Perl (or Perl makes parsing simple?)

We just need to look ahead in the map and search for trees.

my @map = map { chomp; [split(//,$_)] } <STDIN>;
my $w = $map[0]->@*;

my $trees;
my $c=0;
my $r=0;
while (my $pos = $map[$r]->[$c]) {
    $trees++ if $pos eq '#';
    $c = ($c + 3) % $w;
    $r++;
}
say $trees;

Instead of repeating the pattern (as hinted in the instruction, ts, ts), we of course use modulo to keep the horizontal counter inside the map definition.

I still managed to waste at least 5 minutes to a scoping bug:

while (my $pos = $map[$r]->[$c]) {
    $trees++ if $pos eq '#';
    my $c = ($c + 3) % $w;
    $r++;
}

Notice the my before the assignment to $c. Thanks to this I was always checking the first column, for not very correct results...

Part 2

For part two we just need to check a few (5) different ways to calculate where we should look for a tree, so we pack those instructions into an array, and adapt the lookahead to use these values instead of the hardcoded ones.

my @map = map { chomp; [split(//,$_)] } <STDIN>;
my $w = $map[0]->@*;

my @slopes=([1,1],[3,1],[5,1],[7,1],[1,2]);

my $prod=1;
for my $slope (@slopes) {
    my $trees;
    my $c=0;
    my $r=0;
    while (my $pos = $map[$r]->[$c]) {
        $trees++ if $pos eq '#';
        $c = ($c + $slope->[0]) % $w;
        $r += $slope->[1];
    }
    $prod*=$trees;
}
say $prod;

The basic logic stays the same, which would probably look nicer if I would have moved it into a function.

I wasted a few minuts on the second part because I was running the file 03_2.pl but put my changes into an old, buggy version of 03_1.pl - and I was very annoyed why the loop did no stop...

Stats & Links

Comments (via senph)

03.12.2020: Advent of Code Day 2 - counting regex
03.12.2020: Advent of Code Day 1 - brute loops
29.11.2020: My Advent of Code 2019
28.06.2020: Perl Conference in the Cloud report
18.06.2020: How to reclaim disk space used by docker (volumes), but keep a few important ones
29.03.2020: Perl Virtual Events?
29.03.2020: A very late German Perl Workshop 2020 report
04.03.2020: Perl Intro Curriculum
01.03.2020: YEF: shutdown -h
>>>>>>>>>>
<