AoC 2022/3 - Misplaced supplies and where to find them

TL;DR

On with Advent of Code puzzle 3 from 2022: weā€™re definitely gone the abstract way here.

I like the background story of Advent of Code, even though I understand that sometimes it can be difficult to frame a challenge within it. My feeling is that thisā€¦ was one of those times.

The final byproduct in puzzle 1 and, as it is eventually revealed, puzzle 2 is a sum of priorities, which are assigned statically based on the character. So going bottom-up hereā€™s the relevant function:

sub char-to-value ($char) {
   return 1 + $char.ord - 'a'.ord if $char ~~ /<[ a .. z ]>/;
   return 27 + $char.ord - 'A'.ord;
}

OK, with that out of the way, letā€™s look at part 1. Here we have to consider each input line/string as composed of two halves; our task is to find the common character between them, turn it into a value with char-to-value above and sum everything:

sub part1 ($inputs) {
   return $inputs.map({
      my $hlen = ($_.chars / 2).Int;
      my ($h, $l) =
         ($_.substr(0, $hlen), $_.substr($hlen)).map({ $_.comb.Set });
      char-to-value(($h āˆ© $l).keys);
   }).sum;
}

Raku comes with both batteries and a lot of nice tools tailored for a lot of different tasks. In this case:

  • we get each character using comb
  • we donā€™t care about them individually, but treat each half as a set of characters.
  • with two sets available, finding the common character means finding the intersection of the two sets, which is what the āˆ© operator is for.

Part 2 goes on a similar tune, only we have to find the common character across triplets taken from the input. Raku comes to help us with a way to take the intersection of many sets at once with hyperoperator [āˆ©]:

sub part2 ($inputs) {
   gather {
      for @$inputs -> $a, $b, $c {
         take char-to-value(([āˆ©] ($a, $b, $c)Ā».combĀ».Set).keys)
      }
   }.sum;
}

I could not think of some clever/idiomatic way of expressing the concept of taking inputs three at a time, so I just did that with the for loop specification.

This somehow ā€œbreaks the flowā€ for composition, which would make adding a final .sum complicated. So I thought of using gather/take. I like it. Maybe one day it will be efficient, if itā€™s not already.

Full solution.

Now, before leaving, a hint from mschaap:

But you donā€™t have to .Set the lists in order to be able to [āˆ©] them, that is done automatically, see my solution.

I love that thereā€™s always something to learn!

All in all, a nice oneā€¦ stay safe!


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