3 import Prelude hiding (round)
5 import Control.Monad.ST
7 import qualified Data.Vector.Unboxed.Mutable as V
12 do let seed = [20, 0, 1, 11, 6, 3]
18 part1 seed = runGame seed 2020
19 part2 seed = runGame seed 30000000
24 seedGame seed historySize =
25 do round <- newSTRef $ length seed
26 word <- newSTRef $ last seed
27 history <- V.replicate historySize zeroInt
28 forM_ (zip (init seed) [1..]) $ \(t, s) -> V.write history t s
29 return (round, word, history)
31 runGame seed roundsNeeded =
33 do (round, word, history) <- seedGame seed roundsNeeded
34 gameStep roundsNeeded round word history
37 gameStep :: Int -> STRef s Int -> STRef s Int -> V.MVector s Int -> ST s ()
38 gameStep targetRound round word history =
39 do roundVal <- readSTRef round
40 if roundVal == targetRound
43 wordVal <- readSTRef word
44 wordH <- V.read history wordVal
45 let word' = speakWord wordH roundVal
46 V.write history wordVal roundVal
47 modifySTRef round (+1)
49 gameStep targetRound round word history
52 speakWord :: Int -> Int -> Int
54 speakWord prev now = now - prev