openSystem.IOtypeInnerBag={InnerBagName:stringInnerBagQuantity:int}letrecparseInnerBagsacc=function|[]|"no"::"other"::["bags."]->acc|innerQuantity::innerAdj::innerColor::_::rest->letbagName=sprintf"%s %s"innerAdjinnerColorletbag={InnerBagName=bagName;InnerBagQuantity=intinnerQuantity}parseInnerBags(bag::acc)rest|pattern->failwithf"cannot parse inner pattern %A"patternletparseLineacc(s:string)=matchList.ofArray<|s.Split('')with|adj::color::_::_::"no"::"other"::["bags."]->letbagName=sprintf"%s %s"adjcolorMap.addbagName[]acc|adj::color::_::_::rest->letbagName=sprintf"%s %s"adjcolorMap.addbagName(parseInnerBags[]rest)acc|pattern->failwithf"cannot parse pattern %A"patternletrecfindAllBagsContainingsoughtBagallBags=allBags|>Map.filter(fun_innerBags->innerBags|>List.exists(funbag->bag.InnerBagName=soughtBag))|>Map.toList|>List.collect(fst>>funbagName->bagName::findAllBagsContainingbagNameallBags)letreccountBagsInsideOfbagNameallBags=matchMap.tryFindbagNameallBagswith|SomeinnerBags->innerBags|>List.sumBy(funinnerBag->innerBag.InnerBagQuantity+countBagsInsideOfinnerBag.InnerBagNameallBags*innerBag.InnerBagQuantity)|None->0// this should never happenletbags=File.ReadAllLines"input.txt"|>Array.foldparseLineMap.empty// Part 1findAllBagsContaining"shiny gold"bags|>Set.ofList|>Set.count|>printfn"%d"// Part2countBagsInsideOf"shiny gold"bags|>printfn"%d"
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.
F#: