AoC 2021/01 - Up and down


On with Advent of Code puzzle 01 from 2021: some tricky comparisons.

The 2021 edition of Advent of Code started with a trick. In hindsight, it was a sort of manifesto: there will be a lot of brute forcing to do, but you might find a clever solution every now and then.

And so… I was gullible enough to fall in the trap, and implemented it the full way:

#!/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) {
} ## end sub get_inputs ($filename = undef)

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

sub count-increases (@inputs) {
   my $count = (1 .. @inputs.end)
      .map({@inputs[$_] > @inputs[$_ - 1] ?? 1 !! 0 })

sub part1 ($inputs) { return count-increases($inputs) }

sub part2 ($inputs) {
   return count-increases(
      (1 ..^ $inputs.end).map({$inputs[($_-1)..($_+1)].sum})

The trap is in part 2. I’ve been tricked into calculating the sliding window sum, but it was not needed. Consider four consecutive values, yielding two values to be compared:

\[..., x_n, x_{n+1}, x_{n+2}, x_{n+3}, ...\]

The two sums would be:

\[S_n = x_n + x_{n+1} + x_{n+2} \\ S_{n+1} = x_{n+1} + x_{n+2} + x_{n+3}\]

There’s a lot of similarity between the two… because they share two items out of three. So the comparison can be simplified like this:

\[S_n \gtrless S_{n+1} \\ x_n + x_{n+1} + x_{n+2} \gtrless x_{n+1} + x_{n+2} + x_{n+3} \\ x_n \gtrless x_{n+3}\]

So… no need to do sums, it’s sufficient to skip two items for doing the comparison!

Stay safe folks!

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