コード例 #1
0
ファイル: Day07.cs プロジェクト: nattfalk/advent_of_code_2020
 public static long BagsContained(Bag bag)
 {
     return(bag.children.Select(x => x.Value * (BagsContained(x.Key) + 1)).Sum());
 }
コード例 #2
0
        static void Main(string[] args)
        {
            var bagsRegex = new Regex(@"(?:(?<container>.+)\sbags\scontain\s)(?:(?<content>(?:(?<count>\d+)\s+)*(?<name>.+?))\sbag(?:s*)(?:,\s|\.))+", RegexOptions.Compiled);
            var items     = File.ReadLines("input.txt");

            Dictionary <string, Bag> bags = new Dictionary <string, Bag>();

            foreach (var item in items)
            {
                var match = bagsRegex.Match(item);
                if (!match.Success)
                {
                    throw new Exception("error parsing for " + item);
                }

                if (!bags.TryGetValue(match.Groups["container"].Value, out var container))
                {
                    container = new Bag {
                        Name = match.Groups["container"].Value
                    };
                    bags.Add(container.Name, container);
                }

                if (match.Groups["name"].Value == "no other")
                {
                    continue;
                }

                for (var i = 0; i < match.Groups["name"].Captures.Count; i++)
                {
                    var name  = match.Groups["name"].Captures[i].Value;
                    var count = int.Parse(match.Groups["count"].Captures[i].Value);
                    if (!bags.TryGetValue(name, out var bag))
                    {
                        bag = new Bag {
                            Name = name
                        };
                        bags.Add(bag.Name, bag);
                    }

                    bag.Containers.Add(container);
                    container.Bags.Add(name, count);
                }
            }

            var gold = bags["shiny gold"];

            var distinctBags = new HashSet <Bag>();

            void CountUniqContainers(Bag b)
            {
                foreach (var c in b.Containers)
                {
                    distinctBags.Add(c);
                    CountUniqContainers(c);
                }
            }

            CountUniqContainers(gold);
            Console.WriteLine("answer #1: " + distinctBags.Count);

            int CountBags(Bag b)
            {
                var total = 0;

                foreach (var(name, count) in b.Bags)
                {
                    total += count + CountBags(bags[name]) * count;
                }
                return(total);
            }

            Console.WriteLine("answer #2: " + CountBags(gold));
        }
コード例 #3
0
ファイル: Day07.cs プロジェクト: nattfalk/advent_of_code_2020
 public static bool CanContain(Bag bag, Bag inside)
 {
     return(bag.children.Where(x => x.Key == inside || CanContain(x.Key, inside)).Count() > 0);
 }