Explorar o código

Day 22 part 2

Lukas Angerer %!s(int64=2) %!d(string=hai) anos
pai
achega
f76297e9e3
Modificáronse 2 ficheiros con 47 adicións e 0 borrados
  1. 43 0
      Day22/BrickStack.cs
  2. 4 0
      Day22/Program.cs

+ 43 - 0
Day22/BrickStack.cs

@@ -111,6 +111,49 @@ public class BrickStack
         return count;
     }
 
+    public long CountAllFalling()
+    {
+        var supports = new Dictionary<Brick, List<Brick>>();
+        var isSupportedBy = new Dictionary<Brick, List<Brick>>();
+        
+        foreach (var b in _bricks.OrderBy(x => x.MinZ))
+        {
+            supports.TryAdd(b, new List<Brick>());
+            isSupportedBy.TryAdd(b, new List<Brick>());
+            foreach (var above in BricksAbove(b))
+            {
+                supports[b].Add(above);
+
+                isSupportedBy.TryAdd(above, new List<Brick>());
+                isSupportedBy[above].Add(b);
+            }
+        }
+
+        var count = 0L;
+        foreach (var b in _bricks.OrderBy(x => x.MinZ))
+        {
+            // walk "up" the graph to all nodes that only have supports within our "set" starting with the current brick
+            var set = new HashSet<Brick>();
+            var edge = new List<Brick> { b };
+            while (edge.Count > 0)
+            {
+                foreach (var e in edge)
+                {
+                    set.Add(e);
+                }
+
+                edge = edge.SelectMany(e => supports[e])
+                    .Distinct()
+                    .Where(above => isSupportedBy[above].Count(below => !set.Contains(below)) == 0)
+                    .ToList();
+            }
+
+            count += set.Count - 1;
+        }
+
+        return count;
+    }
+
     private Vec Min(params Vec[] vectors)
     {
         var x = vectors[0].X;

+ 4 - 0
Day22/Program.cs

@@ -28,4 +28,8 @@ Console.WriteLine();
 var count = brickStack.CountSafeRemoval();
 Console.WriteLine($"Can be disintegrated: {count}");
 
+Console.WriteLine();
+var total = brickStack.CountAllFalling();
+Console.WriteLine($"Sum of all falling Blocks: {total}");
+
 return 0;