Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Day 6: Lanternfish

day6/solution.livemd

Day 6: Lanternfish

Part 1 and 2

After getting a slight spoiler that star two may grow a whole lot, I gave up on trying to do a Process oriented solution.

Will try to count down from 80 down to 0, keep state on a Map where each key is the age and the value are the count of lantern fish that age.

So, for example, for input 3,4,3,1,2 I’d have initially a Map %{3 => 2, 4 => 1, 1 => 1, 2 => 1}.

On the first tick we iterate through every key and a new map is created with the next population state.

  • So in the first tick we will end up with %{2 => 2, 3 => 1, 0 => 1, 1 => 1}.
  • second tick with %{1 => 2, 2 => 1, 6 => 1, 0 => 1, 8 => 1}
  • third tick with %{0 => 2, 1 => 1, 5 => 1, 6 => 1, 7 => 1, 8 => 1}
  • fourth tick with %{6 => 3, 8 => 2, 0 => 1, 4 => 1, 5 => 1, 7 => 1}
  • and so on
puzzle_input =
  "5,4,3,5,1,1,2,1,2,1,3,2,3,4,5,1,2,4,3,2,5,1,4,2,1,1,2,5,4,4,4,1,5,4,5,2,1,2,5,5,4,1,3,1,4,2,4,2,5,1,3,5,3,2,3,1,1,4,5,2,4,3,1,5,5,1,3,1,3,2,2,4,1,3,4,3,3,4,1,3,4,3,4,5,2,1,1,1,4,5,5,1,1,3,2,4,1,2,2,2,4,1,2,5,5,1,4,5,2,4,2,1,5,4,1,3,4,1,2,3,1,5,1,3,4,5,4,1,4,3,3,3,5,5,1,1,5,1,5,5,1,5,2,1,5,1,2,3,5,5,1,3,3,1,5,3,4,3,4,3,2,5,2,1,2,5,1,1,1,1,5,1,1,4,3,3,5,1,1,1,4,4,1,3,3,5,5,4,3,2,1,2,2,3,4,1,5,4,3,1,1,5,1,4,2,3,2,2,3,4,1,3,4,1,4,3,4,3,1,3,3,1,1,4,1,1,1,4,5,3,1,1,2,5,2,5,1,5,3,3,1,3,5,5,1,5,4,3,1,5,1,1,5,5,1,1,2,5,5,5,1,1,3,2,2,3,4,5,5,2,5,4,2,1,5,1,4,4,5,4,4,1,2,1,1,2,3,5,5,1,3,1,4,2,3,3,1,4,1,1"
"5,4,3,5,1,1,2,1,2,1,3,2,3,4,5,1,2,4,3,2,5,1,4,2,1,1,2,5,4,4,4,1,5,4,5,2,1,2,5,5,4,1,3,1,4,2,4,2,5,1,3,5,3,2,3,1,1,4,5,2,4,3,1,5,5,1,3,1,3,2,2,4,1,3,4,3,3,4,1,3,4,3,4,5,2,1,1,1,4,5,5,1,1,3,2,4,1,2,2,2,4,1,2,5,5,1,4,5,2,4,2,1,5,4,1,3,4,1,2,3,1,5,1,3,4,5,4,1,4,3,3,3,5,5,1,1,5,1,5,5,1,5,2,1,5,1,2,3,5,5,1,3,3,1,5,3,4,3,4,3,2,5,2,1,2,5,1,1,1,1,5,1,1,4,3,3,5,1,1,1,4,4,1,3,3,5,5,4,3,2,1,2,2,3,4,1,5,4,3,1,1,5,1,4,2,3,2,2,3,4,1,3,4,1,4,3,4,3,1,3,3,1,1,4,1,1,1,4,5,3,1,1,2,5,2,5,1,5,3,3,1,3,5,5,1,5,4,3,1,5,1,1,5,5,1,1,2,5,5,5,1,1,3,2,2,3,4,5,5,2,5,4,2,1,5,1,4,4,5,4,4,1,2,1,1,2,3,5,5,1,3,1,4,2,3,3,1,4,1,1"
input = "3,4,3,1,2"

population =
  puzzle_input |> String.split(",") |> Enum.map(&String.to_integer/1) |> Enum.frequencies()

defmodule Part1 do
  def simulate(current_population, 0), do: Enum.sum(Map.values(current_population))

  def simulate(current_population, tick) do
    new_population =
      Enum.reduce(current_population, %{6 => 0, 8 => 0}, fn
        {0, v}, new_population -> %{new_population | 6 => v, 8 => v}
        {k, v}, new_population -> Map.update(new_population, k - 1, v, &(&1 + v))
      end)

    simulate(new_population, tick - 1)
  end
end

IO.puts("Part1: #{Part1.simulate(population, 80)}")
IO.puts("Part2: #{Part1.simulate(population, 256)}")
Part1: 350917
Part2: 1592918715629
:ok