1 {-# LANGUAGE NegativeLiterals #-}
2 {-# LANGUAGE FlexibleContexts #-}
4 import qualified Data.IntMap.Strict as M
5 import Data.IntMap.Strict ((!))
6 import Control.Monad.State.Lazy
8 data Machine = Machine { location :: Int
10 , memory :: M.IntMap Int
15 text <- readFile "data/advent05.txt"
16 let locations = map (readJump) $ lines text
17 let m0 = makeMachine locations
18 print $ evalState stepAll m0
19 print $ evalState stepAllB m0
22 readJump :: String -> Int
25 makeMachine :: [Int] -> Machine
26 makeMachine locations = Machine {location = 0, steps = 0,
27 memory = M.fromList $ zip [0..] locations}
29 stepAll :: State Machine Int
32 if M.member (location m0) (memory m0)
35 else return (steps m0)
37 stepAllB :: State Machine Int
40 if M.member (location m0) (memory m0)
43 else return (steps m0)
45 stepOnce :: State Machine ()
50 let loc' = mem!loc + loc
51 let steps' = steps m0 + 1
52 let mem' = M.insert loc (mem!loc + 1) mem
53 put m0 {location = loc', steps = steps', memory = mem'}
55 stepOnceB :: State Machine ()
60 let loc' = mem!loc + loc
61 let steps' = steps m0 + 1
62 let newVal = if mem!loc >= 3 then (mem!loc - 1) else (mem!loc + 1)
63 let mem' = M.insert loc newVal mem
64 put m0 {location = loc', steps = steps', memory = mem'}