public void Part2() { var myBag = new Suitcase() { Color = "shiny gold", Quantity = 1 }; PopulateBag(myBag); int sum = GetSum(myBag); Console.WriteLine("Part 2: {0}", sum); }
private static int GetSum(Suitcase bag) { /// Recursive method to calculate the cumulative sum for the entire tree int count = 0; if (bag.Children.Count() == 0) { return(0); } bag.Children.ForEach(child => { count += child.Quantity; count += child.Quantity * GetSum(child); }); return(count); }
private void PopulateBag(Suitcase myBag) { /// Generate a tree structure with root node myBag /// Uses Breadth-first search to find all children Queue <Suitcase> bagQueue = new Queue <Suitcase>(); bagQueue.Enqueue(myBag); while (bagQueue.Count > 0) { var currentBag = bagQueue.Dequeue(); var children = GetChildren(currentBag.Color); if (children != null) { currentBag.Children.AddRange(children); currentBag.Children.ForEach(bag => bagQueue.Enqueue(bag)); } } }