advent_of_code/lib/day1.ex
Caleb Webber c2933897db switch to project format
Fixed a bug in the day1 solution where
the list of totals could add the "current
sum" for a given elf to the list each time
a new entry was added e.g. an input like,

100
200
300

could result in a list like,

[300, 200, 100].

Now we reorder the list at each "reset" (empty line).
2023-10-27 15:47:49 -04:00

48 lines
951 B
Elixir

defmodule Day1 do
def to_command(s) do
try do
{:add, s |> String.trim() |> String.to_integer()}
rescue
ArgumentError -> {:reset}
end
end
def get_answer(state) do
elem(state, 1) |>
Enum.reduce(0, fn i, acc -> i + acc end)
end
def init_state() do
{nil, [0, 0, 0], false}
end
def apply_command(command, state) do
case command do
{:add, n} -> apply_add(n, state)
{:reset} -> apply_reset(state)
end
end
defp apply_add(n, state) do
{current, total, exit} = state
new_current = if is_nil(current) do 0 else current end + n
{new_current, total, exit}
end
defp take_top_three(n, list) do
[ n | list ] |>
Enum.sort(:desc) |>
Enum.take(3)
end
defp apply_reset(state) do
{current, total, exit} = state
case current do
nil -> {current, total, true}
_ -> {nil, take_top_three(current, total), exit}
end
end
end