From 6aa3fbaa58883c2fe4b903be3cf15779bc053574 Mon Sep 17 00:00:00 2001 From: Caleb Webber Date: Sat, 28 Oct 2023 01:31:31 -0400 Subject: [PATCH] remove halting logic from day1 --- lib/aoc_runner.ex | 24 +++++++++++++++++++----- lib/day1.ex | 22 +++++++++++----------- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/lib/aoc_runner.ex b/lib/aoc_runner.ex index bd54b28..beb108b 100644 --- a/lib/aoc_runner.ex +++ b/lib/aoc_runner.ex @@ -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 diff --git a/lib/day1.ex b/lib/day1.ex index fbddc3f..aeae8a8 100644 --- a/lib/day1.ex +++ b/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