-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.hs
95 lines (78 loc) · 2.18 KB
/
run.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE RecordWildCards #-}
import Control.Applicative
import Control.Monad (replicateM)
import Data.Maybe (mapMaybe)
data Tree a = Tree { children :: [Tree a],
metadata :: [a] }
deriving (Show, Functor, Foldable, Traversable)
newtype Parser a = Parser { runParser :: [Int] -> [(a, [Int])] }
deriving Functor
instance Applicative Parser where
pure x = Parser $ \input -> [(x, input)]
Parser fp <*> Parser xp = Parser $ \input -> do
(f, fs) <- fp input
(x, xs) <- xp fs
pure (f x, xs)
instance Monad Parser where
return = pure
Parser x >>= mf = Parser $ \input -> do
(a, rest) <- x input
runParser (mf a) rest
instance Alternative Parser where
empty = Parser $ const []
(Parser x) <|> (Parser y) = Parser $ \input ->
case x input of
[] -> y input
result -> result
readMetadata :: Int -> Parser [Int]
readMetadata n = replicateM n readInt
readInt :: Parser Int
readInt = Parser $ \input ->
case input of
[] -> empty
(x:xs) -> [(x, xs)]
readTree :: Parser (Tree Int)
readTree = do
cn <- readInt
mn <- readInt
c <- replicateM cn readTree
m <- readMetadata mn
return $ Tree { children = c, metadata = m }
parse :: Show a => Parser a -> [Int] -> a
parse p input =
case runParser p input of
[] ->
error $ "Parsing failed!"
[(x, [])] ->
x
_:_:_ ->
error $ "Ambiguous"
[(x, rest)] ->
error $ "Parsed: " ++ show x ++ "\nInput remaining: " ++ show rest
parseAll :: String -> Tree Int
parseAll = parse readTree . map read . words
(!?) :: [a] -> Int -> Maybe a
list !? i =
case drop i list of
x:_ -> Just x
_ -> Nothing
value :: Tree Int -> Int
value Tree {..}
| null children = sum metadata
| otherwise = sum
. map value
. mapMaybe (children !?)
. map (+ (-1)) $ metadata
part1 :: Num a => Tree a -> a
part1 = sum
part2 :: Tree Int -> Int
part2 = value
testInput :: String
testInput = "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2"
main :: IO ()
main = do
input <- parseAll <$> readFile "input.txt"
print (part1 input)
print (part2 input)