From 0dc33cafed11aa4574f740b244d96060008ec714 Mon Sep 17 00:00:00 2001 From: Akshay Date: Mon, 7 Dec 2020 12:13:52 +0530 Subject: shorten --- execs/Day07.hs | 11 ++++------- lib/Utils.hs | 4 ++++ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/execs/Day07.hs b/execs/Day07.hs index 1587e2b..72043af 100644 --- a/execs/Day07.hs +++ b/execs/Day07.hs @@ -2,6 +2,7 @@ module Main where import Data.Map (Map) import qualified Data.Map as Map +import Utils myBag = "shiny gold" @@ -19,18 +20,14 @@ parseLine s = (leadingBag, contained) 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 + where inners = map snd $ m Map.! outer 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 +countNested s m = foldl (\acc (c,b) -> acc + c * (1 + countNested b m)) 0 $ m Map.! s 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 $ howMany (canContain q . fst) $ Map.toList q print $ countNested myBag q diff --git a/lib/Utils.hs b/lib/Utils.hs index 1eb42fc..4c9a581 100644 --- a/lib/Utils.hs +++ b/lib/Utils.hs @@ -4,6 +4,7 @@ module Utils ( binaryToInt , right , bet , (&+) + , howMany ) where import Data.Char (digitToInt) @@ -30,3 +31,6 @@ bet k (l, u) = k >= l && k <= u -- combine filter predicates (&+) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool) (&+) = liftM2 (&&) + +howMany :: (a -> Bool) -> [a] -> Int +howMany predicate = length . filter ((== True) . predicate) -- cgit v1.2.3