summaryrefslogtreecommitdiff
path: root/2017/8.hs
blob: 7ac76e323e3ae06e27c41945bc1352bb4880a429 (plain)
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
36
37
38
39
40
41
42
43
44
45
import Control.Monad
import qualified Data.Map.Strict as Map
import Data.Map.Strict ((!))
import Data.Maybe


data Ins = Ins String Int Cond

data Cond = Cond String (Int -> Bool)

type State = Map.Map String Int

initState :: State
initState = Map.empty

condTable :: Map.Map String (Int -> Int -> Bool)
condTable = Map.fromList
    [("<", flip (<))
    ,(">", flip (>))
    ,("<=", flip (<=))
    ,(">=", flip (>=))
    ,("==", flip (==))
    ,("!=", flip (/=))]

parse :: String -> Ins
parse str = case words str of
    [name, "inc", val, "if", cname, op, cval] ->
        Ins name ( read val) (Cond cname ((condTable ! op) (read cval)))
    [name, "dec", val, "if", cname, op, cval] ->
        Ins name (-read val) (Cond cname ((condTable ! op) (read cval)))

exec :: State -> Ins -> State
exec mp (Ins name delta (Cond cname cop)) =
    let val = fromMaybe 0 (Map.lookup name mp)
        cval = fromMaybe 0 (Map.lookup cname mp)
    in if cop cval then Map.insert name (val + delta) mp else mp

main :: IO ()
main = do
    input <- liftM (map parse . lines) (readFile "8.in")

    let states = scanl exec initState input

    print $ maximum $ Map.elems (last states)
    print $ maximum $ map (maximum . (0 :) . Map.elems) states