Struggled on this one more than I probably should have. I started with a recursion bug that was right in front of my eyes, then went on to part2 to realize that I would need to re-think my model (can't say I didn't see that one coming).
Part 1
publicclassPart1:Puzzle<Dictionary<string,Node<Bag>>,long>{protectedconststringTarget="shiny gold";publicoverridelongSampleAnswer=>4;publicoverrideDictionary<string,Node<Bag>>ParseInput(stringrawInput)=>rawInput.Split(Environment.NewLine).Where(line=>line.Length>0).Select(ParseBagDescription).ToDictionary(node=>node.Name,node=>node);Node<Bag>ParseBagDescription(stringdescription){varparts=description.Split(" bags contain ");varname=parts[0];varnode=newNode<Bag>(name,newBag(name));varinnerBagNodes=parts[1].Split(',').Where(description=>description!="no other bags.").Select(bag=>bag.TrimStart()).Select(bag=>ParseBagContents(bag)).Select(bag=>newNode<Bag>(bag.Name,bag));node.AddChildren(innerBagNodes);returnnode;}BagParseBagContents(stringcontents){intspace=contents.IndexOf(' ');stringname=contents[(space+1)..contents.LastIndexOf(' ')];int.TryParse(contents[..space],outintcount);returnnewBag(name,count);}publicoverridelongSolve(Dictionary<string,Node<Bag>>input)=>input.Count(x=>HasDescendent(input,Target,x.Value));boolHasDescendent(Dictionary<string,Node<Bag>>allNodes,stringname,Node<Bag>node)=>node.Children.Any(n=>n.Name==Target||HasDescendent(allNodes,name,allNodes[n.Name]));}
Part2
publicclassPart2:Part1{publicoverridelongSampleAnswer=>32;publicoverridelongSolve(Dictionary<string,Node<Bag>>input)=>CountInnerBagsRecursive(input,input[Target])-1;// We counted the target bag, reduce count by 1.longCountInnerBagsRecursive(Dictionary<string,Node<Bag>>allNodes,Node<Bag>node)=>node.Children.Aggregate(1L,(acc,cur)=>acc+=cur.Value.Count*CountInnerBagsRecursive(allNodes,allNodes[cur.Name]));}
Struggled on this one more than I probably should have. I started with a recursion bug that was right in front of my eyes, then went on to part2 to realize that I would need to re-think my model (can't say I didn't see that one coming).
Part 1
Part2
Node