AoC 2021/02 - Ready, set, go!

TL;DR

On with Advent of Code puzzle 2 from 2021: moving around.

This day’s puzzle is… doable. Remember that I was at the beginning, so I was egager to use stuff from Raku:

#!/usr/bin/env raku
use v6;

sub MAIN ($filename = $?FILE.subst(/\.raku$/, '.sample')) {
   my $inputs = get-inputs($filename);
   my ($part1, $part2) = solve($inputs);

   my $highlight = "\e[1;97;45m";
   my $reset     = "\e[0m";
   put "part1 $highlight$part1$reset";
   put "part2 $highlight$part2$reset";
}

sub get-inputs ($filename) {
   $filename.IO.basename.IO.lines.map: { .split: /\s+/ };
} ## end sub get_inputs ($filename = undef)

subset Depth of Int where * >= 0;

sub solve ($inputs) {
   return (part1($inputs), part2($inputs));
}

sub part1 ($inputs) {
   my (Depth $depth, $hp) = 0, 0;
   for @$inputs -> $command {
      my ($direction, $amount) = @$command;
      given $direction {
         when 'forward' { $hp += $amount    }
         when 'up'      { $depth -= $amount }
         when 'down'    { $depth += $amount }
         default        { die 'WTF?!?'      }
      }
   }
   return $hp * $depth;
}

sub part2 ($inputs) {
   my (Depth $depth, $hp, $aim) = 0, 0, 0;
   for @$inputs -> $command {
      my ($direction, $amount) = @$command;
      given $direction {
         when 'forward' { $hp += $amount; $depth += $aim * $amount }
         when 'up'      { $aim -= $amount }
         when 'down'    { $aim += $amount }
         default        { die 'WTF?!?'    }
      }
   }
   return $hp * $depth;
}

This time I was intrigued by given/when to express the operations to be done. Apart from this, it was only a matter of following the instructions!

OK, enough for today then… Stay safe!


Comments? Octodon, , GitHub, Reddit, or drop me a line!