-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDay06.hs
35 lines (29 loc) · 988 Bytes
/
Day06.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
34
35
module AOC2017.Day06 (day06a, day06b) where
import AOC2017.Types (Challenge)
import qualified Data.Map as M
import qualified Data.Vector as V
step :: V.Vector Int -> V.Vector Int
step v = V.accum (+) v' [ (i `mod` V.length v, 1)
| i <- [maxIx + 1 .. maxIx + maxBlocks]
]
where
maxIx = V.maxIndex v
maxBlocks = v V.! maxIx
v' = v V.// [(maxIx, 0)]
-- | Returns the location of the first loop, and the length of the loop
findLoop :: Ord a => [a] -> (Int, Int)
findLoop = go 0 M.empty
where
go _ _ [] = error "Infinite list expected."
go n m (x:xs) = case M.lookup x m of
Just l -> (n, l)
Nothing -> go (n + 1) (M.insert x 1 m') xs
where
m' = succ <$> m
day06 :: String -> (Int, Int)
day06 = findLoop . iterate step
. V.fromList . map read . words
day06a :: Challenge
day06a = show . fst . day06
day06b :: Challenge
day06b = show . snd . day06