3 import Prelude hiding (round)
5 import Control.Monad.ST
7 import qualified Data.Vector.Unboxed.Mutable as V
10 type STInt s = STRef s Int
11 type VInt s = V.MVector s Int
15 do let seed = [20, 0, 1, 11, 6, 3]
21 part1 seed = runGame seed 2020
22 part2 seed = runGame seed 30000000
24 runGame :: [Int] -> Int -> Int
25 runGame seed roundsNeeded =
27 do (round, word, history) <- seedGame seed roundsNeeded
28 gameSteps roundsNeeded round word history
31 seedGame :: [Int] -> Int -> ST s (STInt s, STInt s, VInt s)
32 seedGame seed historySize =
33 do round <- newSTRef $ length seed
34 word <- newSTRef $ last seed
35 history <- V.replicate historySize 0
36 forM_ (zip (init seed) [1..]) $ \(t, s) -> V.write history t s
37 return (round, word, history)
40 -- gameSteps :: Int -> STRef s Int -> STRef s Int -> V.MVector s Int -> ST s ()
41 gameSteps :: Int -> STInt s -> STInt s -> VInt s -> ST s ()
42 gameSteps targetRound round word history =
43 do roundVal <- readSTRef round
44 if roundVal == targetRound
47 wordVal <- readSTRef word
48 wordH <- V.read history wordVal
49 let word' = speakWord wordH roundVal
50 V.write history wordVal roundVal
51 modifySTRef round (+1)
53 gameSteps targetRound round word history
56 speakWord :: Int -> Int -> Int
58 speakWord prev now = now - prev