示例#1
0
        public override object GetAnswerTwo()
        {
            BagRule[] rules = GetRules().ToArray();
            BagRule   br    = rules.Single(it => it.Name == "shiny gold");

            return(br.CountInside(rules));
        }
示例#2
0
        public static void Day7()
        {
            Console.WriteLine("Day7: ");
            Dictionary <string, BagRule> rules = File.ReadAllLines("Aoc2020\\Day07\\input.txt").Select(rule => new BagRule(rule)).ToDictionary(rule => rule.Color);

            // part 1
            bool CanContain(string outercolor, string color)
            {
                BagRule outerBag = rules[outercolor];

                if (outerBag.ContentRules.ContainsKey(color))
                {
                    return(true);
                }
                foreach (var innerBag in outerBag.ContentRules)
                {
                    if (CanContain(innerBag.Key, color))
                    {
                        return(true);
                    }
                }
                return(false);
            }

            int count = 0;

            foreach (var bag in rules.Keys)
            {
                if (CanContain(bag, "shiny gold"))
                {
                    count++;
                }
            }
            Console.WriteLine(count);

            // part 2
            int CountContents(string color)
            {
                BagRule bag   = rules[color];
                int     count = 0;

                foreach (var innerBag in bag.ContentRules)
                {
                    count += innerBag.Value * CountContents(innerBag.Key) + innerBag.Value;
                }
                return(count);
            }

            Console.WriteLine(CountContents("shiny gold"));
        }