module one import StdEnv import Data.Func import qualified Data.Map from Data.Map import :: Map(..), fromList, get, find, keys, foldrWithKey, findWithDefault import Text read :: *File -> [Char] read f # (ok, l, f) = freadc f | not ok = [] = [l:read f] Start w # (io, w) = stdio w # bag = fromList (makeBag (read io)) = (one ['shiny gold'] bag, two bag ['shiny gold']-1) one color bag = length $ filter id $ map (canContain bag color) $ filter ((<>)color) $ keys bag two bag color = 1+sum[n*two bag c\\(n, c)<-findWithDefault [] color bag] makeBag :: [Char] -> [([Char], [(Int, [Char])])] makeBag ls = [(b, mkItem c)\\[b,c]<-map (split [' contain ']) $ split ['.\n'] ls] where mkItem :: [Char] -> [(Int, [Char])] mkItem s = [(toInt (toString x), join [' '] xs)\\[x:xs]<-map (split [' ']) (split [', '] s)] canContain bag color name = or [name == color:[canContain bag color child\\(n, child)<-findWithDefault [] name bag]]