Aoc Day1

Advent of code, day 1

It’s that time of year again. Day 1: Trebuchet?!.

We’re asked to take a bunch of strings, and find the first and last digit, treat those as a 2-digit integer, and sum them up. Here’s my version in Dyalog APL:

      data←⊃⎕NGET'd/1'1
      day1←{+/⍎⍕(⊣/,⊢/)¨⍵∩¨⊂⎕D}
      day1 data ⍝ part 1
55477

All well and good. No magic – find the intersection of each string with ⎕D, which is the string ‘0123456789’. Pick the first and last (⊣/,⊢/), convert to int ⍎⍕ and sum.

For part two, it turns out that the strings may contain numbers spelled with letters, e.g. ‘seven3one’. Before we get ahead of ourselves, there are some interesting issues with this, like ‘zfxbzhczcx9eightwockk’. Note how the last digit should be 2, and not 8. There are several ways we could attack this. I was in a hurry, so took the ugliest but simplest approach, to pre-process the strings with some regexing:

      day1 'oneight' 'eightwo' 'nineight' 'twone' 'sevenine' 'eighthree' 'one' 'two' 'three' 'four' 'five' 'six' 'seven' 'eight' 'nine'⎕R (⍕¨18 82 98 21 79 83 1 2 3 4 5 6 7 8 9)⊢data
54431

However, someone here at Dyalog proposed the following:

      +/((10⊥¯9+@(9∘<)1⍳⍤1⍨((⊂⌊/,⌈/)∘⍸∨⌿)⌷⍉)∘↑(1↓⎕D,(⎕C∊∘⎕A⊂⊢)'OneTwoThreeFourFiveSixSevenEightNine')⍷¨⊂)¨data
54431

Decoding that is left as an exercise for the aspiring padawan.

Written on December 1, 2023