using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace _2021___Day_14
{
class Program
{
public static void Main()
{
var input = File.ReadAllLines("../../../../Input.in");
var template = input.First();
var rules = input.Skip(2)
.Select(line => line.Split(" -> "))
.ToDictionary(x => x[0], x => x[1][0]);
Console.WriteLine("After 10 steps : " + polymerize(10));
Console.WriteLine("After 40 steps : " + polymerize(40));
long polymerize(int steps)
{
var pairs = rules.ToDictionary(r => r.Key, r => new Regex(r.Key).Matches(template).LongCount());
var letters = Enumerable.Range(0, 26).Select(i => (char)('A' + i))
.ToDictionary(c => c, c => template.LongCount(t => t == c));
for (int i = 0; i < steps; i++)
{
foreach (var line in rules)
{
letters[line.Value] += pairs[line.Key];
}
pairs = rules.ToDictionary(r => r.Key, r => rules
.Where(x => x.Key.Insert(1, x.Value.ToString()).Contains(r.Key))
.Sum(x => pairs[x.Key]));
}
var polymer = letters.Where(c => c.Value > 0).OrderBy(d => d.Value);
return polymer.Last().Value - polymer.First().Value;
}
}
}
}