#define Day14 #if Day14 using System.Text.RegularExpressions; using AoC2021; var text = File.ReadAllText("day14/input").Split("\n\n"); var startOne = text[0].Select(x => x).ToList(); var startTwo = startOne.ToList(); var reg = new Regex(@"(?\w)(?\w) -> (?\w)"); var rules = reg.Matches(text[1]).Select(m => new Rule(new Pair(m.Groups["a"].Value[0], m.Groups["b"].Value[0]), m.Groups["res"].Value[0])).ToDictionary(x => x.p, x=> x.res); // for (var i = 0; i < 10; i++) { // var next = new List(); // for (int pos = 1; pos < startOne.Count; pos++) { // var res = rules[new Pair(startOne[pos - 1], startOne[pos])]; // next.Add(startOne[pos - 1]); // next.Add(res); // } // next.Add(startOne.Last()); // startOne = next; // } // // var charCountPartOne = startOne.GroupBy(s => s).ToDictionary(g => g.Key, g => g.LongCount()); // Console.WriteLine(charCountPartOne.Values.Max() - charCountPartOne.Values.Min()); // // var charCountPartTwo = rules.Keys.SelectMany(r => new List(){r.a, r.b}).Distinct().ToDictionary(x => x, _ => 0L); int maxDepth = 40; var finalCount = new Dictionary(); var save = new Dictionary>(); Dictionary Bla(Pair cur, int depth) { var curKey = new AsKey(cur, depth); if (save.ContainsKey(curKey)) { return save[curKey]; } if (depth <= 0) { return new Dictionary() { {cur.a, 1} }; } var c = rules[cur]; var first = Bla(new Pair(cur.a, c), depth - 1); var second = Bla(new Pair(c, cur.b), depth - 1); var merged = Merge(first, second); save[curKey] = merged.ToDictionary(x => x.Key, x => x.Value); return merged; } Dictionary Merge(Dictionary a, Dictionary b) { var merged = new Dictionary(); foreach (var k in a.Keys) { merged.Add(k, a[k]); } foreach (var k in b.Keys) { if (merged.ContainsKey(k)) { merged[k] += b[k]; } else { merged[k] = b[k]; } } return merged; } for (int pos = 1; pos < startTwo.Count; pos++) { var countBla = Bla(new Pair(startTwo[pos - 1], startTwo[pos]), maxDepth); finalCount = Merge(finalCount, countBla); } finalCount[startTwo.Last()]++; Console.WriteLine(finalCount.Values.Max() - finalCount.Values.Min()); record AsKey(Pair p, int depth); record Rule(Pair p, char res); record Pair(char a, char b); #endif