Advent Of Code

Chapter 04: Barcode shenanigans

Even in the North Pole people ask me to fix printers

Today’s stop is the top secret North Pole port. Not really my cup of tea, it’s windy and wet, the temperature is way too cold for me.

Unfortunately, the elves can’t find the parabolas they’re looking for. The bad weather has damaged the barcodes they were using and they need to reprint everything in a cheap and efficient way.

Fortunately for them, it’s cold, I want to get back on the train, and therefore I’m very motivated to help them.

Part one

The problem is the following: barcodes are printed with the letters “roygbv” (again?), but some letters have been damaged and are shown as ‘?’. For examples, here are some barcodes:

rgbrgbrgbr
?rv
o??v???y
??bg?v??
??b?????
???
type Input = [String]

type Output = Int

parseInput :: String -> Input
parseInput = lines

The printer can repeat a sequence of instructions as many times as possible, even cropping the last iteration of said sequence. What we need to find is the smallest subsequence we can use in order to write the whole barcode (because the printer isn’t free and the elves pay per character they use in their instruction).

My idea is pretty simple:

But this isn’t enough in itself, we need to handle the ‘?’s. Doing that is quite simple:

isValidPrefix :: String -> String -> Bool
isValidPrefix "" _ = True
isValidPrefix xs prefix =
  and (zipWith isValidPair prefix xs)
    && isValidPrefix (drop prefixLen xs) (zipWith fixValue prefix xs)
  where
    prefixLen = length prefix
    fixValue a b = case a of '?' -> b; _ -> a
    isValidPair a b = a == '?' || b == '?' || a == b

findSmallestPrefix :: String -> String
findSmallestPrefix barcode = findJust (isValidPrefix barcode) prefixes
  where
    prefixes = tail $ inits barcode

Now we just need to find the smallest prefix for every barcode in the input, get the prefix length and sum them all:

partOne :: Input -> Output
partOne = sum . map (length . findSmallestPrefix)

Part two

The elves just told me that there is only one single barcode. The linebreaks were mistakes (this printer sure is unreliable during bad weather!)

Well, that is no problem: just concat them all into one long barcode and find the length of the smallest prefix:

partTwo :: Input -> Output
partTwo = length . findSmallestPrefix . concat

And voilà!

Chapter Epilogue

That was fast! Cold is a really good motivator :) Time to get back onto the train, I’m freezing!

–

I’m a bit surprised that there wasn’t more to do during part two. This felt a bit too easy. I’m worried about tomorrow now :d