remove halting logic from day1
This commit is contained in:
parent
c2933897db
commit
6aa3fbaa58
2 changed files with 30 additions and 16 deletions
|
@ -1,15 +1,29 @@
|
|||
defmodule AOCRunner do
|
||||
defp is_empty(s) do
|
||||
(s |> String.trim() |> String.length()) == 0
|
||||
end
|
||||
|
||||
def run(advent) do
|
||||
result = IO.stream() |>
|
||||
{_, state} = IO.stream() |>
|
||||
Enum.reduce_while(
|
||||
advent.init_state(),
|
||||
{nil, advent.init_state()},
|
||||
fn line, acc -> line
|
||||
|> advent.to_command()
|
||||
|> advent.apply_command(acc)
|
||||
|> then(fn acc -> if elem(acc, 2) do {:halt, acc} else {:cont, acc} end end)
|
||||
|> then(fn command ->
|
||||
{u, state} = acc
|
||||
{u, advent.apply_command(command, state)}
|
||||
end)
|
||||
|> then(fn {u, s} ->
|
||||
if (line |> is_empty()) && (u |> is_empty()) do
|
||||
{:halt, {u, s}}
|
||||
else
|
||||
{:cont, {u, s}}
|
||||
end
|
||||
end)
|
||||
|> then(fn {reduce_atom, {_, state}} -> {reduce_atom, {String.trim(line), state}} end)
|
||||
end
|
||||
)
|
||||
|
||||
IO.puts(advent.get_answer(result))
|
||||
IO.puts(advent.get_answer(state))
|
||||
end
|
||||
end
|
||||
|
|
22
lib/day1.ex
22
lib/day1.ex
|
@ -8,12 +8,12 @@ defmodule Day1 do
|
|||
end
|
||||
|
||||
def get_answer(state) do
|
||||
elem(state, 1) |>
|
||||
elem(state, 1) |>
|
||||
Enum.reduce(0, fn i, acc -> i + acc end)
|
||||
end
|
||||
|
||||
def init_state() do
|
||||
{nil, [0, 0, 0], false}
|
||||
{nil, [0, 0, 0]}
|
||||
end
|
||||
|
||||
def apply_command(command, state) do
|
||||
|
@ -24,24 +24,24 @@ defmodule Day1 do
|
|||
end
|
||||
|
||||
defp apply_add(n, state) do
|
||||
{current, total, exit} = state
|
||||
new_current = if is_nil(current) do 0 else current end + n
|
||||
{current, total} = state
|
||||
new_current = n + if is_nil(current) do 0 else current end
|
||||
|
||||
{new_current, total, exit}
|
||||
{new_current, total}
|
||||
end
|
||||
|
||||
defp take_top_three(n, list) do
|
||||
[ n | list ] |>
|
||||
[ 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}
|
||||
{current, total} = state
|
||||
if !is_nil(current) do
|
||||
{nil, take_top_three(current, total)}
|
||||
else
|
||||
state
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Add table
Reference in a new issue