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
|
defmodule AOCRunner do
|
||||||
|
defp is_empty(s) do
|
||||||
|
(s |> String.trim() |> String.length()) == 0
|
||||||
|
end
|
||||||
|
|
||||||
def run(advent) do
|
def run(advent) do
|
||||||
result = IO.stream() |>
|
{_, state} = IO.stream() |>
|
||||||
Enum.reduce_while(
|
Enum.reduce_while(
|
||||||
advent.init_state(),
|
{nil, advent.init_state()},
|
||||||
fn line, acc -> line
|
fn line, acc -> line
|
||||||
|> advent.to_command()
|
|> advent.to_command()
|
||||||
|> advent.apply_command(acc)
|
|> then(fn command ->
|
||||||
|> then(fn acc -> if elem(acc, 2) do {:halt, acc} else {:cont, acc} end end)
|
{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
|
end
|
||||||
)
|
)
|
||||||
|
|
||||||
IO.puts(advent.get_answer(result))
|
IO.puts(advent.get_answer(state))
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
18
lib/day1.ex
18
lib/day1.ex
|
@ -13,7 +13,7 @@ defmodule Day1 do
|
||||||
end
|
end
|
||||||
|
|
||||||
def init_state() do
|
def init_state() do
|
||||||
{nil, [0, 0, 0], false}
|
{nil, [0, 0, 0]}
|
||||||
end
|
end
|
||||||
|
|
||||||
def apply_command(command, state) do
|
def apply_command(command, state) do
|
||||||
|
@ -24,10 +24,10 @@ defmodule Day1 do
|
||||||
end
|
end
|
||||||
|
|
||||||
defp apply_add(n, state) do
|
defp apply_add(n, state) do
|
||||||
{current, total, exit} = state
|
{current, total} = state
|
||||||
new_current = if is_nil(current) do 0 else current end + n
|
new_current = n + if is_nil(current) do 0 else current end
|
||||||
|
|
||||||
{new_current, total, exit}
|
{new_current, total}
|
||||||
end
|
end
|
||||||
|
|
||||||
defp take_top_three(n, list) do
|
defp take_top_three(n, list) do
|
||||||
|
@ -37,11 +37,11 @@ defmodule Day1 do
|
||||||
end
|
end
|
||||||
|
|
||||||
defp apply_reset(state) do
|
defp apply_reset(state) do
|
||||||
{current, total, exit} = state
|
{current, total} = state
|
||||||
|
if !is_nil(current) do
|
||||||
case current do
|
{nil, take_top_three(current, total)}
|
||||||
nil -> {current, total, true}
|
else
|
||||||
_ -> {nil, take_top_three(current, total), exit}
|
state
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
Loading…
Add table
Reference in a new issue