refresh y2022d1
used more pattern matching to simplify function bodies
This commit is contained in:
parent
09ee6c41cc
commit
e2fa206ac9
1 changed files with 17 additions and 50 deletions
|
@ -1,36 +1,18 @@
|
|||
defmodule Day1 do
|
||||
def get_answer(state) do
|
||||
{_, total, part} = state
|
||||
def get_answer({_, total, :part1}), do: total
|
||||
def get_answer({_, totals, :part2}), do: totals |> Enum.reduce(0, fn i, acc -> i + acc end)
|
||||
|
||||
total
|
||||
|> then(fn total ->
|
||||
case part do
|
||||
:part1 -> total
|
||||
:part2 -> total |> Enum.reduce(0, fn i, acc -> i + acc end)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
def init_state(part) do
|
||||
case part do
|
||||
:part1 -> {nil, 0, part}
|
||||
:part2 -> {nil, [0, 0, 0], part}
|
||||
end
|
||||
end
|
||||
def init_state(:part1 = p), do: {nil, 0, p}
|
||||
def init_state(:part2 = p), do: {nil, [0, 0, 0], p}
|
||||
|
||||
def execute(line, state) do
|
||||
apply_command(
|
||||
line |> to_command(),
|
||||
state
|
||||
)
|
||||
line
|
||||
|> to_command()
|
||||
|> apply_command(state)
|
||||
end
|
||||
|
||||
defp apply_command(command, state) do
|
||||
case command do
|
||||
{:add, n} -> apply_add(n, state)
|
||||
{:reset} -> apply_reset(state)
|
||||
end
|
||||
end
|
||||
defp apply_command({:add, n}, state), do: apply_add(n, state)
|
||||
defp apply_command({:reset}, state), do: apply_reset(state)
|
||||
|
||||
defp to_command(s) do
|
||||
try do
|
||||
|
@ -40,36 +22,21 @@ defmodule Day1 do
|
|||
end
|
||||
end
|
||||
|
||||
defp apply_add(n, state) do
|
||||
{current, total, part} = state
|
||||
|
||||
new_current =
|
||||
n +
|
||||
if is_nil(current) do
|
||||
0
|
||||
else
|
||||
current
|
||||
end
|
||||
|
||||
{new_current, total, part}
|
||||
end
|
||||
defp apply_add(n, {nil, total, part}), do: {n, total, part}
|
||||
defp apply_add(n, {current, total, part}), do: {n + current, total, part}
|
||||
|
||||
defp take_top_three(n, list) do
|
||||
[n | list]
|
||||
|> Enum.sort(:desc)
|
||||
|> Enum.take(3)
|
||||
|> Enum.sort(:desc)
|
||||
|> Enum.take(3)
|
||||
end
|
||||
|
||||
defp apply_reset({nil, _, _} = state), do: state
|
||||
defp apply_reset(state) do
|
||||
{current, total, part} = state
|
||||
|
||||
if !is_nil(current) do
|
||||
case part do
|
||||
:part1 -> {nil, max(total, current), part}
|
||||
:part2 -> {nil, take_top_three(current, total), part}
|
||||
end
|
||||
else
|
||||
state
|
||||
case part do
|
||||
:part1 -> {nil, max(total, current), part}
|
||||
:part2 -> {nil, take_top_three(current, total), part}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Add table
Reference in a new issue