Advent of Code 2021 Day 14

part 1:

part 2:


Just like day 7 spent some time on optimizing part 1 and it paid off :smiley:

1 Like

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


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 |>{&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. :slight_smile:

1 Like

Sure. Here’s the link: AoC 14 2021 INPUT -

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.


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 ( … once you get past the syntax you’ll see it is very similar to your solution :slight_smile:

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

  def run(freq, formulas, count) do
    freq =
      Enum.reduce(freq, freq, fn
        {{p1, p2} = pair, count}, acc ->
          case formulas do
            %{^pair => insertion} ->
              |> 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))

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

    run(freq, formulas, count - 1)

full solution here.