Example #1
0
        public bool Solve(int part = 0)
        {
            string[] towerSpecs = File.ReadAllLines("Day07/input.txt");
            Dictionary <string, Tower> towers = new Dictionary <string, Tower>();
            Regex regex = new Regex(@"^(\w+) \((\d+)\)\s?(-> ([\w\s,]+))?$");

            Tower GetTower(string name)
            {
                if (towers.TryGetValue(name, out Tower t))
                {
                    return(t);
                }
                else
                {
                    var newTower = new Tower(name);
                    towers.Add(name, newTower);
                    return(newTower);
                }
            }

            foreach (string spec in towerSpecs)
            {
                Match m = regex.Match(spec);

                var tower = GetTower(m.Groups[1].Value);
                tower.Weight = int.Parse(m.Groups[2].Value);

                if (m.Groups[4].Success)
                {
                    foreach (var subTowerName in m.Groups[4].Value.Split(", "))
                    {
                        tower.AddSubtower(GetTower(subTowerName));
                    }
                }
            }

            var bottomTower = towers.Values.First(t => t.SubTowers.Count > 0 && !t.HasParent);

            if (part == 2)
            {
                var faultyTower = bottomTower;
                while (faultyTower != null)
                {
                    var unbalancedSubTower = faultyTower.SubTowers.FirstOrDefault(t => !t.IsBalanced);
                    if (unbalancedSubTower == null)
                    {
                        var weightGroups =
                            from sub in faultyTower.SubTowers
                            group sub by sub.GetCombinedWeight() into g
                            select g;

                        int correctWeight    = weightGroups.Where(g => g.Count() > 1).Select(g => g.Key).First();
                        var wrongWeightTower = weightGroups.First(g => g.Count() == 1).First();
                        int weightDiff       = wrongWeightTower.GetCombinedWeight() - correctWeight;

                        Console.WriteLine($"{wrongWeightTower.Name} weight is {wrongWeightTower.Weight}, should be {wrongWeightTower.Weight - weightDiff}");
                    }

                    faultyTower = unbalancedSubTower;
                }
            }
            else
            {
                Console.WriteLine(bottomTower.Name);
            }

            return(true);
        }
Example #2
0
 public Tower(string Name, Tower Parent)
 {
     this.Name   = Name;
     this.Parent = Parent;
     SubTowers   = new List <Tower>();
 }
Example #3
0
 public void AddSubtower(Tower subtower)
 {
     subtower.HasParent = true;
     _subtowers.Add(subtower);
 }