Today’s Advent of Code puzzle is the simplest code of the year to date. And I’m making it longer for posting than what I solved with.
It’s as literate Haskell as usual, but it really won’t take long. First two imports.
import Control.Arrow ((&&&))
import Data.List (findIndex,nub,tails)
We’re looking for a start-of-message marker, defined as
w
distinct characters. Here’s a function to identify
whether we’re looking at that. It works by extracting the w
first characters of its input, and checking whether removing duplicates
is a no-op.
isMessageStart :: Int -> String -> Bool
take w -> pfx) = nub pfx == pfx isMessageStart w (
Finding the start-of-message end is now a simple matter of iterating, and adjusting the resulting index for prefix length.
locate :: Int -> String -> Maybe Int
= fmap (+ w) . findIndex (isMessageStart w) . tails locate w
A simple wrapper to perform both parts in a single sitting, and we’re done!
main :: IO ()
= interact $ show . (locate 4 &&& locate 14) main
This concludes today’s puzzle. See you tomorrow!