// Counts how many individual bags are required inside a shiny gold bag. // Starts at shiny gold bag and go down the tree of contents. public string PartTwo() { var BagsToContents = MapBagsToContents(); var nBags = 0; var bagStack = new Stack <BagRequirement>(); foreach (var bag in BagsToContents["shiny gold"]) { bagStack.Push(bag); } while (bagStack.Count > 0) { var currentBag = bagStack.Pop(); nBags += currentBag.nRequired; if (BagsToContents.ContainsKey(currentBag.Bag)) { foreach (var bag in BagsToContents[currentBag.Bag]) { var newBag = new BagRequirement(); newBag.Bag = bag.Bag; newBag.nRequired = bag.nRequired * currentBag.nRequired; bagStack.Push(newBag); } } } return(nBags.ToString()); }
private void AddToBagsToContentsMap(string bag, string content, int nRequired, Dictionary <string, List <BagRequirement> > bagsToContents) { var newBag = new BagRequirement(); newBag.Bag = content; newBag.nRequired = nRequired; if (bagsToContents.ContainsKey(bag)) { bagsToContents[bag].Add(newBag); } else { var bags = new List <BagRequirement>(); bags.Add(newBag); bagsToContents.Add(bag, bags); } }