# Advent of Code 2021 Day 14

part 1:

part 2:

2 Likes

Just like day 7 spent some time on optimizing part 1 and it paid off
y2021/day_14.ex

1 Like
3 Likes

Oh, those small everyday learnings. Today it was `Enum.min_max_by/4`.

4 Likes

Got a bit stuck on part2 today but reading some solutions here helped me sort it out. Iâ€™m learning a ton from you all!

1 Like

F# won the toss so solved it with F# and got back here to see how Elixir solutions were like. Surprisingly, my F# solution looked very much like yours here, so I tried running yours with my input (test case ran fine). But it didnâ€™t work out. Looks like due to the line `|> Enum.map(&{&1, 1})` where youâ€™re collecting the pair count got me because I had a pair repeat (i.e. two â€śPKâ€ť-s). I guess a frequency there could fix it?

No idea. I will check that tomorrow. Could you please send me your input? Here or via a DM.

1 Like

Sure. Hereâ€™s the link: AoC 14 2021 INPUT - Pastebin.com

The answers are: `3118` and `4332887448171`

I probably spent too much time on approaches that didnâ€™t work. The â€śeureka!â€ť moment for me was realizing that I had to track both the pairs AND individual letters. From there, it was simple to implement.

Solution here.

2 Likes

Got it done just under the wire. Code is ugly but not going to pretty it up until tomorrow. Had the same â€śaha!â€ť of tracking both pairs and individual counts as @APB9785 did. I just need to organize my initialization steps better.

You were right. Thanks a lot for finding that bug. With my input, it didnâ€™t have an effect. With yours it did.
My answers were `2408` and `2651311098752` so probably just some lucky coincidence.
BTW: where can I take a look at your F# solution? I am quite curious.

1 Like

Here it is. AoCFs/Day14.fs at main Â· code-shoily/AoCFs (github.com) â€¦ once you get past the syntax youâ€™ll see it is very similar to your solution

1 Like

I was stuck on it for a while but finally got it. The main module:

``````defmodule Recursion do
def run(freq, _, 0) do
freq
end

def run(freq, formulas, count) do
freq =
Enum.reduce(freq, freq, fn
{{p1, p2} = pair, count}, acc ->
case formulas do
%{^pair => insertion} ->
acc
|> Map.update(pair, -count, &(&1 - count))
|> Map.update({p1, insertion}, count, &(&1 + count))
|> Map.update({insertion, p2}, count, &(&1 + count))
|> Map.update(insertion, count, &(&1 + count))
end

{n, _}, acc when is_integer(n) ->
acc
end)

run(freq, formulas, count - 1)
end
end
``````

full solution here.