-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay24.hs
64 lines (50 loc) · 1.88 KB
/
Day24.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
52
53
54
55
56
57
58
59
60
61
62
63
64
module Day24
( part1
, part2
) where
import Control.Monad.State.Lazy (State)
import Data.List.Split (chunksOf, splitOn)
import Data.Map (Map, fromList)
import Data.Maybe (Maybe (Just, Nothing), isJust)
type Step = (Maybe [Int] -> Int -> Maybe [Int])
data MONAD a =
MONAD [Step] a
push :: Int -> Maybe [Int] -> Int -> Maybe [Int]
push modifier stack val = (val + modifier :) <$> stack
pop :: Int -> Maybe [Int] -> Int -> Maybe [Int]
pop modifier stack val
| Just val == fmap ((+ modifier) . head) stack = fmap tail stack
| otherwise = Nothing
toInst :: [[String]] -> Step
toInst s
| last (s !! 4) == "1" = push (read . last $ s !! 15)
| last (s !! 4) == "26" = pop (read . last $ s !! 5)
extendNumbers1 :: [[Int]] -> [[Int]]
extendNumbers1 = concatMap (\x -> map (\y -> x ++ [y]) [9,8 .. 1])
extendNumbers2 :: [[Int]] -> [[Int]]
extendNumbers2 = concatMap (\x -> map (\y -> x ++ [y]) [1 .. 9])
runMonad :: MONAD (Maybe [Int]) -> [Int] -> Maybe [Int]
runMonad (MONAD _ result) [] = result
runMonad (MONAD (s:teps) result) (i:nt) = runMonad (MONAD teps (s result i)) nt
steps :: String -> [Step]
steps = map toInst . chunksOf 18 . map (splitOn " ") . lines
toMonad :: [Step] -> MONAD (Maybe [Int])
toMonad steps = MONAD steps (Just [])
allModels :: [[Int]] -> ([[Int]] -> [[Int]]) -> MONAD (Maybe [Int]) -> [[Int]]
allModels models extendNumbers monad
| length (head models) == 14 = models
| otherwise =
allModels
(filter (isJust . runMonad monad) . extendNumbers $ models)
extendNumbers
monad
part1 :: Bool -> String -> String
part1 _ =
show .
foldl (\a b -> b + 10 * a) 0 .
head . allModels [[]] extendNumbers1 . toMonad . steps
part2 :: Bool -> String -> String
part2 _ =
show .
foldl (\a b -> b + 10 * a) 0 .
head . allModels [[]] extendNumbers2 . toMonad . steps