These are getting trickier. The first part was easy, the second, well, needed to re-do first one to make it performant. I guess that quote where they say “Our greatest shortcomings is the inebility to comprehend exponential growth” is true – at least for me.
Anyways, I did do pigeonhole sort in Elixir few days ago, and a similar idea can be applied here… bucket em up.
defmodule AdventOfCode.Y2021.Day06 do
use AdventOfCode.Helpers.InputReader, year: 2021, day: 6
def run_1, do: input!() |> parse() |> multiply(80) |> Enum.sum()
def run_2, do: input!() |> parse() |> multiply(256) |> Enum.sum()
def parse(f), do: f |> String.split(",") |> Enum.map(&String.to_integer/1) |> Enum.frequencies()
def multiply(fishes, day) do
(day == 0 && Map.values(fishes)) ||
multiply(
Map.pop(fishes, 0)
|> then(
&Map.merge(
for({k, v} <- elem(&1, 1), into: %{}, do: {k - 1, v}),
%{6 => elem(&1, 0) || 0, 8 => elem(&1, 0) || 0},
fn _, a, b -> a + b end
)
),
day - 1
)
end
end