From 72cce948973068ba3556d7329c7909f5367a36b5 Mon Sep 17 00:00:00 2001 From: Ben Harris Date: Tue, 14 Dec 2021 11:41:00 -0500 Subject: d14p2 --- aoc2021.test/DayTests.cs | 2 +- aoc2021/Day14.cs | 40 ++++++++++++++++++++++++++++++++++++---- 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(); + 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(); + 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(); + 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); } -- cgit 1.4.1