-
Notifications
You must be signed in to change notification settings - Fork 5
/
Day08.hs
52 lines (44 loc) · 1.28 KB
/
Day08.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
module AOC2017.Day08 (day08a, day08b) where
import AOC2017.Types (Challenge)
import Data.Foldable (toList)
import Data.List (foldl', scanl')
import qualified Data.Map as M
data Instr = Instr { _iRegister :: String
, _iUpdate :: Int
, _iCondReg :: String
, _iPredicate :: Int -> Bool
}
step :: M.Map String Int -> Instr -> M.Map String Int
step m (Instr r u c p)
| p (M.findWithDefault 0 c m) = M.insertWith (+) r u m
| otherwise = m
parse :: String -> [Instr]
parse = map parseLine . lines
day08a :: Challenge
day08a = show . maximum
. foldl' step M.empty
. parse
day08b :: Challenge
day08b = show . maximum . foldMap toList
. scanl' step M.empty
. parse
parseLine :: String -> Instr
parseLine (words->r:f:u:_:c:o:x:_) =
Instr { _iRegister = r
, _iUpdate = f' (read u)
, _iCondReg = c
, _iPredicate = (`op` read x)
}
where
f' = case f of
"dec" -> negate
_ -> id
op = case o of
">" -> (>)
">=" -> (>=)
"<" -> (<)
"<=" -> (<=)
"==" -> (==)
"!=" -> (/=)
_ -> error "Invalid op"
parseLine _ = error "No parse"