private static bool ContainsRequiredColour( IReadOnlyDictionary <string, ColouredBag> bagRules, HashSet <string> containsColour, ColouredBag bagRule, string requiredColour) { if (containsColour.Contains(requiredColour)) { return(true); } var mayContainRequiredColour = false; if (bagRule.RequiredInnerBags.Count == 0) { mayContainRequiredColour = false; } else if (bagRule.RequiredInnerBags.ContainsKey(requiredColour)) { mayContainRequiredColour = true; } else { foreach (var innerBagRule in bagRule.RequiredInnerBags) { var innerBagPermits = ContainsRequiredColour( bagRules, containsColour, bagRules[innerBagRule.Key], requiredColour); mayContainRequiredColour |= innerBagPermits; if (innerBagPermits) { break; } } } return(mayContainRequiredColour); }
public static void Solve() { var inputs = Tools.GetInput(7); var bagRules = new Dictionary <string, ColouredBag>(); foreach (var ruleDefinition in inputs) { var bag = new ColouredBag(ruleDefinition); bagRules[bag.Colour] = bag; } // Part 1. var coloursThatMayContainShinyGold = new HashSet <string>(); ContainsRequiredColour(bagRules, coloursThatMayContainShinyGold, "shinygold"); var permittedColours = string.Concat(coloursThatMayContainShinyGold.Select(s => $"{s}, ")); Console.WriteLine($"May contain ShinyGold = {coloursThatMayContainShinyGold.Count}. {permittedColours}"); // Part 2. var bagsRequiredForShinyGold = RequiredBags(bagRules, new Dictionary <string, int>(), "shinygold"); Console.WriteLine($"Bags required for ShinyGold = {bagsRequiredForShinyGold}. (Including ShinyGold one too)."); }