Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Day9 where
- import Control.Applicative
- import Text.Megaparsec
- import Text.Megaparsec.String
- import Data.Tree
- import Data.Monoid
- import Data.Maybe
- import Control.Monad (void)
- import Text.Printf
- fooP :: Parser (Tree (Maybe String))
- fooP =
- garbageP <|> groupP
- garbageP :: Parser (Tree (Maybe String))
- garbageP = do
- void $ char '<'
- Node . Just . catMaybes <$> manyTill (ignoreP <|> Just <$> anyChar) (char '>') <*> return []
- where
- ignoreP = char '!' >> anyChar >> return Nothing
- groupP :: Parser (Tree (Maybe String))
- groupP = do
- void $ char '{'
- things <- fooP `sepBy` char ','
- void $ char '}'
- return $ Node Nothing things
- score :: Tree (Maybe t) -> Tree Int
- score =
- score' 1
- where
- score' n (Node v ch) =
- case v of
- Nothing -> Node n (map (score' (n + 1)) ch)
- Just _ -> Node 0 (map (score' n) ch)
- run :: IO ()
- run = do
- input <- readFile "data/day9"
- let res = parse fooP "day9" input
- case res of
- Left e -> print e
- Right r -> do
- printf "Sum of scores is %d\n" (getSum . foldMap Sum $ score r)
- printf "Sum of garbage lengths is %d\n" (getSum . fromJust . foldMap (fmap Sum) $ fmap (fmap length) r)
Add Comment
Please, Sign In to add comment