about summary refs log tree commit diff
diff options
context:
space:
mode:
authorBen Harris <ben@tilde.team>2021-12-14 11:41:00 -0500
committerBen Harris <ben@tilde.team>2021-12-14 11:41:00 -0500
commit72cce948973068ba3556d7329c7909f5367a36b5 (patch)
treed4e7285ee4df9b82ee07cf53c7fb553899d4517a
parentf77d93de7e137764b8336a238546c2256c7f9a9b (diff)
d14p2
-rw-r--r--aoc2021.test/DayTests.cs2
-rw-r--r--aoc2021/Day14.cs40
2 files changed, 37 insertions, 5 deletions
diff --git a/aoc2021.test/DayTests.cs b/aoc2021.test/DayTests.cs
index 177f7d7..18add59 100644
--- a/aoc2021.test/DayTests.cs
+++ b/aoc2021.test/DayTests.cs
@@ -34,7 +34,7 @@ public class DayTests
     [DataRow(typeof(Day11), "1613", "510")]
     [DataRow(typeof(Day12), "4549", "120535")]
     [DataRow(typeof(Day13), "837", Day13Actual)]
-    [DataRow(typeof(Day14), "5656", "")]
+    [DataRow(typeof(Day14), "5656", "12271437788530")]
     public void CheckAllDays(Type dayType, string part1, string part2)
     {
         var s = Stopwatch.StartNew();
diff --git a/aoc2021/Day14.cs b/aoc2021/Day14.cs
index e4facd7..db931c2 100644
--- a/aoc2021/Day14.cs
+++ b/aoc2021/Day14.cs
@@ -37,6 +37,41 @@ public sealed class Day14 : Day
         return result.ToString();
     }
 
+    private long Solve(int steps)
+    {
+        var moleculeCounts = new Dictionary<string, long>();
+        foreach (var i in Enumerable.Range(0, _template.Length - 1))
+        {
+            var k = _template.Substring(i, 2);
+            moleculeCounts[k] = moleculeCounts.GetValueOrDefault(k) + 1;
+        }
+
+        foreach (var i in Enumerable.Range(0, steps))
+        {
+            var updated = new Dictionary<string, long>();
+            foreach (var (molecule, count) in moleculeCounts)
+            {
+                var (a, n, b) = (molecule[0], _substitutionPairs[molecule], molecule[1]);
+                updated[$"{a}{n}"] = updated.GetValueOrDefault($"{a}{n}") + count;
+                updated[$"{n}{b}"] = updated.GetValueOrDefault($"{n}{b}") + count;
+            }
+
+            moleculeCounts = updated;
+        }
+        
+        var elementCounts = new Dictionary<char, long>();
+        foreach (var (molecule, count) in moleculeCounts)
+        {
+            var a = molecule[0];
+            elementCounts[a] = elementCounts.GetValueOrDefault(a) + count;
+        }
+
+        // don't forget the last letter of the original template
+        elementCounts[_template.Last()]++;
+
+        return elementCounts.Values.Max() - elementCounts.Values.Min();
+    }
+
     public override object Part1()
     {
         var s = Enumerable.Range(0, 10).Aggregate(_template, (current, _) => DoStep(current));
@@ -50,8 +85,5 @@ public sealed class Day14 : Day
         return most.First() - most.Last();
     }
 
-    public override object Part2()
-    {
-        return "";
-    }
+    public override object Part2() => Solve(40);
 }