-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday8.hs
36 lines (31 loc) · 1.1 KB
/
day8.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
36
{-# LANGUAGE ViewPatterns #-}
import qualified Data.Map as Map
import Data.Foldable (toList)
import System.Environment (getArgs)
data Instr = Instr String Int String (Int -> Bool)
parseLine :: String -> Instr
parseLine (words -> r:f:u:_:c:o:x:_) = Instr r (f' (read u)) c (`op` read x)
where
f' = case f of
"dec" -> negate
_ -> id
op = case o of
"!=" -> (/=)
"==" -> (==)
"<=" -> (<=)
">=" -> (>=)
"<" -> (<)
">" -> (>)
_ -> undefined
execInstr :: Map.Map String Int -> Instr -> Map.Map String Int
execInstr m (Instr r u ce cf) | cf (Map.findWithDefault 0 ce m) = Map.insertWith (+) r u m
| otherwise = m
main :: IO()
main = do
filename:_ <- getArgs
contents <- readFile filename
let instructions = map parseLine $ lines contents
putStr "Largest value: "
print $ maximum $ foldl execInstr Map.empty instructions
putStr "Highest value during execution: "
print $ maximum $ foldMap toList $ scanl execInstr Map.empty instructions