-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.hs
33 lines (27 loc) · 1.2 KB
/
Solution.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
module Day09.Solution (part1, part2, xmasCypher, encryptionWeakness, rollingChunks') where
import Advent.Utils (combinations, parseInts)
import Data.Foldable (find)
import Data.Maybe (fromJust)
import Day09.Utils (rollingChunks)
part1 :: String -> String
part1 = show . fromJust . xmasCypher 25
part2 :: String -> String
part2 = show . (encryptionWeakness <$> (fromJust . xmasCypher 25) <*> parseInts)
xmasCypher :: Int -> String -> Maybe Int
xmasCypher size = fmap snd . find (uncurry followsPreamble) . rollingChunks' size . parseInts
where
followsPreamble :: [Int] -> Int -> Bool
followsPreamble preamble target = not $ any ((== target) . sum) (combinations 2 preamble)
rollingChunks' :: Int -> [a] -> [([a], a)]
rollingChunks' size = zip <$> rollingChunks size <*> drop size
encryptionWeakness :: Int -> [Int] -> Int
encryptionWeakness target = go 1
where
go :: Int -> [Int] -> Int
go size ns
| sum contiguousRange < target = go (succ size) ns
| sum contiguousRange == target = minimum contiguousRange + maximum contiguousRange
| sum contiguousRange > target = go 1 (tail ns)
| otherwise = error "this should never happen"
where
contiguousRange = take size ns