From d7e77b3e9d8c9f30d34b46aac119521eb1589717 Mon Sep 17 00:00:00 2001 From: Akshay Date: Mon, 7 Dec 2020 11:26:53 +0530 Subject: add initial solution for day07 --- execs/Day06.hs | 5 +---- execs/Day07.hs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 4 deletions(-) create mode 100644 execs/Day07.hs (limited to 'execs') diff --git a/execs/Day06.hs b/execs/Day06.hs index c35fd21..475f819 100644 --- a/execs/Day06.hs +++ b/execs/Day06.hs @@ -1,11 +1,8 @@ module Main where -import Data.Char (digitToInt) -import Data.List (sort) -import Data.Set (Set) +import Data.Set (Set) import qualified Data.Set as Set -import Control.Monad parseLines :: [String] -> [String] parseLines allLines = unwords first : next diff --git a/execs/Day07.hs b/execs/Day07.hs new file mode 100644 index 0000000..1587e2b --- /dev/null +++ b/execs/Day07.hs @@ -0,0 +1,36 @@ +module Main where + +import Data.Map (Map) +import qualified Data.Map as Map + +myBag = "shiny gold" + +parseContained :: [String] -> [(Int, String)] +parseContained [] = [] +parseContained (count:b:c:_:rest) = (read count, unwords [b,c]):parseContained rest + +parseLine :: [String] -> (String, [(Int, String)]) +parseLine s = (leadingBag, contained) + where leadingBag = unwords $ take 2 s + trailingBags = drop 4 s + contained = case head trailingBags of + "no" -> [] + _ -> parseContained trailingBags + +canContain :: Map String [(Int, String)] -> String -> Bool +canContain m outer = myBag `elem` inners || any (canContain m) inners + where (Just inners) = map snd <$> Map.lookup outer m + +countNested :: String -> Map String [(Int, String)] -> Int +countNested s m = if null l + then 0 + else sum $ map counter l + where (Just l) = Map.lookup s m + counter (count, bag) = count + count * countNested bag m + +main :: IO () +main = do + n <- map (parseLine . words) . lines <$> readFile "input/07" + let q = Map.fromList n + print $ length $ filter (== True) $ map (canContain q . fst) $ Map.toList q + print $ countNested myBag q -- cgit v1.2.3