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.
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:
rgbrgb the prefixes are r, rg, rgb, rgbr, rgbrg and rgbrgb) starting with the smallestBut this isn’t enough in itself, we need to handle the ‘?’s. Doing that is quite simple:
o?? and we’re checking against ?vr, then the first letters are considered equal, because ‘?’ in the string is a wildcard, the second and third are equal because ‘?’ in the prefix is a wildcard, and we can now consider that the prefix should be seen as ovr when comparing the next three characters, as it is the only way this prefix could work for that string with what we’ve seen so far.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)
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à!
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