static void Main(string[] args) { var lines = File.ReadAllLines(".\\input.txt"); Regex outerBagPattern = new Regex("[a-z ]*(?= bags contain)"); Regex innerBagPattern = new Regex(@"(?<count>\d+) (?<color>[a-z ]+)(?= bags?[,\.])"); var bagDict = new Dictionary <string, BagNode>(); foreach (string line in lines) { string containerName = outerBagPattern.Match(line).Value; var containedBags = innerBagPattern.Matches(line).OfType <Match>().Select(m => BagNode.GetLink(int.Parse(m.Groups["count"].Value), m.Groups["color"].Value)); BagNode.AddNode(containerName, containedBags); } BagNode.SetReverseLinks(); BagNode start = BagNode.AllBags["shiny gold"]; // Part one Console.WriteLine(GetContainers(start).Distinct().Count()); // Part two Console.WriteLine(GetContainedCount(start)); Console.Read(); }
public static void AddNode(string name, IEnumerable <BagLink> contents) { BagNode container; if (!AllBags.ContainsKey(name)) { container = new BagNode(name); AllBags.Add(name, container); } else { container = AllBags[name]; } container.Contains.AddRange(contents); }
public static BagLink GetLink(int count, string name) { BagNode node; if (AllBags.ContainsKey(name)) { node = AllBags[name]; } else { node = new BagNode(name); AllBags.Add(name, node); } return(new BagLink() { Count = count, Bag = node }); }
private BagNode BuildNodeFromModel(BagRuleModel bagRuleModel, IList <BagNode> allNodes, IDictionary <string, BagRuleModel> modelDictionary) { var node = new BagNode(bagRuleModel.BagColor); foreach (var(color, qty) in bagRuleModel.AllowedContents) { var childNode = GetNodeForColor(color, allNodes, modelDictionary); node.ChildNodes.Add(new NodeLink(childNode, qty)); childNode.ParentLinks.Add(new NodeLink(node, 1)); } return(node); }
private static int GetContainedCount(BagNode node) { return(node.Contains.Sum(l => l.Count + l.Count * GetContainedCount(l.Bag))); }
private static IEnumerable <BagNode> GetContainers(BagNode node) { return(node.ContainedBy.Select(l => l.Bag) .Union(node.ContainedBy.SelectMany(l => GetContainers(l.Bag)))); }