1
0
Fork 0
adventofcode/8.hs

50 lines
1.4 KiB
Haskell
Raw Normal View History

import Data.HashMap (Map, alter, empty, toList, findWithDefault)
2017-12-08 08:27:09 +00:00
data Instruction = I {
reg :: String,
val :: Int,
2017-12-08 08:27:09 +00:00
src :: String,
fnc :: Int -> Bool
}
getFnc :: String -> (Int -> Int -> Bool)
getFnc s = case s of
"<" -> (<)
"<=" -> (<=)
">" -> (>)
">=" -> (>=)
"==" -> (==)
"!=" -> (/=)
addToMaybe :: Int -> Maybe Int -> Maybe Int
addToMaybe i (Just x) = Just $ i + x
addToMaybe i Nothing = Just i
parseLine :: String -> Instruction
parseLine s =
let (register : operation : value : _ : source : function : argument : _) = words s
2017-12-08 08:27:09 +00:00
in I {
reg = register,
val = case operation of
2017-12-08 08:27:09 +00:00
"inc" -> read value
"dec" -> (- read value),
src = source,
fnc = flip (getFnc function) $ read argument
}
2017-12-08 08:34:34 +00:00
executeInstruction :: (Map String Int, Int) -> Instruction -> (Map String Int, Int)
executeInstruction (m, highest) (I r v s f) =
let value = findWithDefault 0 s m
newHighest = max highest $ findWithDefault highest r m
in if f value
then (alter (addToMaybe v) r m, newHighest)
else (m, highest)
2017-12-08 08:27:09 +00:00
main :: IO ()
main = do
input <- readFile "8.txt"
let instructions = map parseLine $ lines input
2017-12-08 08:34:34 +00:00
(finalMap, highest) = foldl executeInstruction (empty, 0) instructions
2017-12-08 08:27:09 +00:00
maxValue = maximum . snd . unzip . toList $ finalMap
2017-12-08 08:34:34 +00:00
print $ maxValue
print $ highest