<jupyter_start><jupyter_text>--- Day 14: Extended Polymerization --- [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/oddrationale/AdventOfCode2021FSharp/main?urlpath=lab%2Ftree%2FDay14.ipynb) The incredible pressures at this depth are starting to put a strain on your submarine. The submarine has polymerization equipment that would produce suitable materials to reinforce the submarine, and the nearby volcanically-active caves should even have the necessary input elements in sufficient quantities.The submarine manual contains instructions for finding the optimal polymer formula; specifically, it offers a polymer template and a list of pair insertion rules (your puzzle input). You just need to work out what polymer would result after repeating the pair insertion process a few times.For example:NNCBCH -&gt; BHH -&gt; NCB -&gt; HNH -&gt; CHB -&gt; CHC -&gt; BHN -&gt; CNN -&gt; CBH -&gt; HNC -&gt; BNB -&gt; BBN -&gt; BBB -&gt; NBC -&gt; BCC -&gt; NCN -&gt; CThe first line is the polymer template - this is the starting point of the process.The following section defines the pair insertion rules. A rule like AB -&gt; C means that when elements A and B are immediately adjacent, element C should be inserted between them. These insertions all happen simultaneously.So, starting with the polymer template NNCB, the first step simultaneously considers all three pairs:The first pair (NN) matches the rule NN -&gt; C, so element C is inserted between the first N and the second N.The second pair (NC) matches the rule NC -&gt; B, so element B is inserted between the N and the C.The third pair (CB) matches the rule CB -&gt; H, so element H is inserted between the C and the B.Note that these pairs overlap: the second element of one pair is the first element of the next pair. Also, because all pairs are considered simultaneously, inserted elements are not considered to be part of a pair until the next step.After the first step of this process, the polymer becomes NCNBCHB.Here are the results of a few steps using the above rules:Template:     NNCBAfter step 1: NCNBCHBAfter step 2: NBCCNBBBCBHCBAfter step 3: NBBBCNCCNBBNBNBBCHBHHBCHBAfter step 4: NBBNBNBBCCNBCNCCNBBNBBNBBBNBBNBBCBHCBHHNHCBBCBHCBThis polymer grows quickly. After step 5, it has length 97; After step 10, it has length 3073. After step 10, B occurs 1749 times, C occurs 298 times, H occurs 191 times, and N occurs 865 times; taking the quantity of the most common element (B, 1749) and subtracting the quantity of the least common element (H, 161) produces 1749 - 161 = 1588.Apply 10 steps of pair insertion to the polymer template and find the most and least common elements in the result. What do you get if you take the quantity of the most common element and subtract the quantity of the least common element?<jupyter_code>let input = File.ReadAllText(@"input/14.txt").Split(Environment.NewLine + Environment.NewLine)

let template = input.[0]
let insertionRules = 
    input.[1].Split(Environment.NewLine)
    |> Seq.map (fun line -> line.Split(" -> "))
    |> Seq.map (fun split -> (split.[0].[0], split.[0].[1]), split.[1] |> char)
    |> Map

let templateMap = 
    template
    |> Seq.pairwise
    |> Seq.countBy id
    |> Seq.map (fun (key, count) -> key, bigint count)
    |> Map
let step insertionRules (templateMap: Map<char * char, bigint>) =
    let expand (key, value) = 
        let insert = insertionRules |> Map.find key
        [
            (fst key, insert), value
            (insert, snd key), value
        ]
    
    templateMap
    |> Map.toSeq
    |> Seq.map expand
    |> Seq.concat
    |> Seq.groupBy (fun (key, count) -> key)
    |> Seq.map (fun (key, counts) -> 
        key, 
        counts 
        |> Seq.map (fun (_, count) -> count)
        |> Seq.sum)
    |> Map

let rec steps insertionRules templateMap = 
    seq {
        yield templateMap
        yield! 
            templateMap
            |> step insertionRules
            |> steps insertionRules
    }
let countsByChar lastChar (templateMap: Map<char * char, bigint>) = 
    templateMap
    |> Map.toSeq
    |> Seq.map (fun (key, count) -> fst key, count)
    |> Seq.append [(lastChar, 1)]
    |> Seq.groupBy (fun (key, count) -> key)
    |> Seq.map (fun (key, counts) -> 
        key, 
        counts 
        |> Seq.map (fun (_, count) -> count)
        |> Seq.sum)
    |> Map
#!time
templateMap
|> steps insertionRules
|> Seq.item 10
|> countsByChar (template |> Seq.last)
|> fun charCounts -> 
    charCounts
    |> Map.values
    |> Seq.min
    |> (-) (charCounts
        |> Map.values
        |> Seq.max)<jupyter_output><empty_output><jupyter_text>--- Part Two --- The resulting polymer isn't nearly strong enough to reinforce the submarine. You'll need to run more steps of the pair insertion process; a total of 40 steps should do it.In the above example, the most common element is B (occurring 2192039569602 times) and the least common element is H (occurring 3849876073 times); subtracting these produces 2188189693529.Apply 40 steps of pair insertion to the polymer template and find the most and least common elements in the result. What do you get if you take the quantity of the most common element and subtract the quantity of the least common element?<jupyter_code>#!time
templateMap
|> steps insertionRules
|> Seq.item 40
|> countsByChar (template |> Seq.last)
|> fun charCounts -> 
    charCounts
    |> Map.values
    |> Seq.min
    |> (-) (charCounts
        |> Map.values
        |> Seq.max)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09195816804904436, 'fraction_numerical': 0.020375045077533356, 'mean_word_length': 3.3505882352941176, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 71, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '269913', 'license': 'MIT', 'n_tokens_mistral': 1785, 'n_tokens_neox': 1582, 'n_words': 697, 'path': 'Day14.ipynb', 'repo_name': 'oddrationale/AdventOfCode2021FSharp', 'size': '5546'}