Last active
December 6, 2021 18:15
-
-
Save ericridgeway/bd43b097052b04a80834f75328cd90fa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Advent6 do | |
def tick_and_count(input, n) do | |
input | |
|> raw_to_int_list | |
|> tick(n) | |
|> Enum.count | |
end | |
def tick_and_count_efficient(input, n) do | |
input | |
|> raw_to_int_list | |
|> list_to_totals_map | |
|> tick_effecient(n) | |
|> Map.values | |
|> Enum.sum | |
end | |
defp tick(list, 0), do: Enum.map(list, & &1) | |
defp tick(list, n) do | |
list | |
|> decrease_all_but_0s | |
|> for_each_old_0_add_8_to_list | |
|> old_0s_become_6s | |
|> tick(n-1) | |
end | |
defp tick_effecient(totals_map, 0), do: totals_map | |
defp tick_effecient(prev, n) do | |
get_previous = &Map.get(prev, &1) | |
%{ | |
0 => get_previous.(1), | |
1 => get_previous.(2), | |
2 => get_previous.(3), | |
3 => get_previous.(4), | |
4 => get_previous.(5), | |
5 => get_previous.(6), | |
6 => get_previous.(7) + get_previous.(0), | |
7 => get_previous.(8), | |
8 => get_previous.(0), | |
} | |
|> tick_effecient(n-1) | |
end | |
defp decrease_all_but_0s(int_list) do | |
int_list | |
|> Stream.map(fn | |
0 -> :s | |
fish -> fish-1 | |
end) | |
end | |
defp for_each_old_0_add_8_to_list(decreased_stream) do | |
old_0_count = Enum.count(decreased_stream, & &1 == :s) | |
new_8s = List.duplicate(8, old_0_count) | |
decreased_stream | |
|> Stream.concat(new_8s) | |
end | |
defp old_0s_become_6s(decreased_and_new_8s) do | |
decreased_and_new_8s | |
|> Stream.map(fn | |
:s -> 6 | |
fish -> fish | |
end) | |
end | |
defp list_to_totals_map(list) do | |
defaults = | |
0..8 | |
|> Enum.map(&{&1, 0}) | |
|> Map.new | |
Map.merge(defaults, Enum.frequencies(list)) | |
end | |
defp raw_to_int_list(input) do | |
input | |
|> Shared.clean | |
|> String.split(",") | |
|> Enum.map(&String.to_integer/1) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment