I start to like parsing these kind of rules in Haskell, it's very intuitive to me.
The association list was a nice fit for this problem; had I done it in Java, I would have used a Map with Lists as a value. Even though it's not the most time efficient approach, it was allright for this size problem.
solve1::String->Intsolve1input=letassocList=createInvertedMap$mapparseRule$linesinputrecursion=recurse1assocList"shinygold"inlength$nubrecursionrecurse1::[(String,String)]->String->[String]recurse1assocListsearch=letcurrent=lookupAllassocListsearchnext=concatMap(recurse1assocList)currentincurrent++nextsolve2::String->Intsolve2input=letassocList=mapparseRule$linesinputrecursion=recurse2assocList"shinygold"inrecursionrecurse2::[(String,[(String,Int)])]->String->Intrecurse2assocListsearch=letcurrent=concat$lookupAllassocListsearchnext=sum$maprecurseValuecurrentinsum(mapsndcurrent)+nextwhererecurseValue(bag,multiplier)=multiplier*recurse2assocListbag-- parse one line into an association listparseRule::String->(String,[(String,Int)])parseRulea=letkeyValue=splitOn" contain "akey=concat$take2$words$headkeyValuevalue=mapparseContains$splitOn","$keyValue!!1in(key,value)-- "contain 2 shiny gold bags." -> ("shinygold", 2)parseContains::String->(String,Int)parseContains"no other bags."=("none",0)parseContainsa=letremovePeriod=filter(/='.')anoBags=filter(\x->x/="bags"&&x/="bag")$wordsremovePeriodin(concat$tailnoBags,read$headnoBags)-- unwrap the association listcreateInvertedMap::[(String,[(String,b)])]->[(String,String)]createInvertedMap=concatMapinvertwhereinvert(outer,inner)=map((,outer).fst)inner-- a lookup that returns more than one resultlookupAll::[(String,b)]->String->[b]lookupAllassocListkey=mapsnd$filter(\(k,_)->k==key)assocList
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I start to like parsing these kind of rules in Haskell, it's very intuitive to me.
The association list was a nice fit for this problem; had I done it in Java, I would have used a Map with Lists as a value. Even though it's not the most time efficient approach, it was allright for this size problem.