Skip to content

Instantly share code, notes, and snippets.

@saevarb
Created December 10, 2017 22:47
Show Gist options
  • Save saevarb/390fce4dedf16e2552b03d94570cfcd3 to your computer and use it in GitHub Desktop.
Save saevarb/390fce4dedf16e2552b03d94570cfcd3 to your computer and use it in GitHub Desktop.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment