Day 8, parts 1 & 2: Initial solutions.

This commit is contained in:
Jesse D. McDonald 2018-12-08 00:09:41 -06:00
parent 3be1e8fae3
commit d9bce28737
3 changed files with 59 additions and 0 deletions

26
Day8/Part1.hs Executable file
View File

@ -0,0 +1,26 @@
#! /usr/bin/env stack
-- stack --resolver lts-12.20 --install-ghc script
{-# LANGUAGE DeriveFunctor, DeriveFoldable #-}
module Main where
import qualified Control.Monad.State as St
import qualified Data.List as L
import qualified Data.Monoid as Mo
data Node a = Node [Node a] a deriving (Show, Functor, Foldable)
main :: IO ()
main = interact $ show . Mo.getSum . foldMap (foldMap Mo.Sum) . parseTree
parseTree :: String -> Node [Int]
parseTree = St.evalState parseNode
parseNode :: St.State String (Node [Int])
parseNode = do
nChildren <- parseInt
nMetadata <- parseInt
Node <$> St.replicateM nChildren parseNode
<*> St.replicateM nMetadata parseInt
parseInt :: St.State String Int
parseInt = read <$> St.state (L.break (== ' ') . L.dropWhile (== ' '))

32
Day8/Part2.hs Executable file
View File

@ -0,0 +1,32 @@
#! /usr/bin/env stack
-- stack --resolver lts-12.20 --install-ghc script
module Main where
import qualified Control.Monad.State as St
import qualified Data.List as L
data Node = Node [Node] [Int] deriving (Show)
main :: IO ()
main = interact $ show . treeValue . parseTree
treeValue :: Node -> Int
treeValue (Node cs ms)
| null cs = sum ms
| otherwise = sum [ vs !! (m - 1) | m <- ms, 1 <= m, m <= ncs ]
where
vs = map treeValue cs
ncs = length cs
parseTree :: String -> Node
parseTree = St.evalState parseNode
parseNode :: St.State String Node
parseNode = do
nChildren <- parseInt
nMetadata <- parseInt
Node <$> St.replicateM nChildren parseNode
<*> St.replicateM nMetadata parseInt
parseInt :: St.State String Int
parseInt = read <$> St.state (L.break (== ' ') . L.dropWhile (== ' '))

1
Day8/input.txt Normal file

File diff suppressed because one or more lines are too long