AoC Day 9 – Encoding Error

This is a solution to Advent of Code 2020 day 9, written in Raku.

Part One

The first step of attacking the weakness in the XMAS data is to find the first number in the list (after the preamble) which is not the sum of two of the 25 numbers before it. What is the first number that does not have this property?


For part one, I use a sliding window of the input array. For each iteration I take a slice and generate the sum of combinations to see if any match the current value.

  my @numbers = '9-input.txt'.IO.lines;

  for 25..^@numbers.elems -> $n {
      my @window = @numbers[$n-25..$n-1];
      my $next = @numbers[$n];
      my @results = @window.combinations(2).map({ [+] $_ }).grep({$_ == $next});
      say $next if @results.elems == 0

Part Two

The final step in breaking the XMAS encryption relies on the invalid number you just found: you must find a contiguous set of at least two numbers in your list which sum to the invalid number from step 1.

What is the encryption weakness in your XMAS-encrypted list of numbers?


Part two uses a brute-force search of ever longer sequences of numbers to find a match.

  my @numbers = '9-input.txt'{+$_});
  my $elems = @numbers.elems;

  for 1..^$elems -> $n {
      for ^($elems - $n) -> $s {
          my @candidates = @numbers[$s .. $s + $n];
          my $sum = [+] @candidates;
          if $sum == 258585477 {
              say (@candidates.min + @candidates.max);
comments powered by Disqus