about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--day1.exs37
1 files changed, 31 insertions, 6 deletions
diff --git a/day1.exs b/day1.exs
index 5a684c2..08b99b7 100644
--- a/day1.exs
+++ b/day1.exs
@@ -1,7 +1,32 @@
-File.stream!("day1.in")
-|> Stream.map(fn x ->
-  x |> String.trim() |> String.replace_leading("+", "") |> String.to_integer()
-end)
-|> Enum.sum()
-|> IO.puts()
+defmodule Day1 do
+  @initial_state %{found: [], sum: 0}
 
+  def get_numlist do
+    File.stream!("day1.in")
+    |> Stream.map(&String.to_integer(String.trim(&1)))
+  end
+
+  def find_first_repeat(numlist, acc \\ @initial_state) do
+    res = find_repeat(numlist, acc)
+
+    find_first_repeat(numlist, res)
+  end
+
+  def find_repeat(numlist, acc_init) do
+    numlist
+    |> Enum.reduce(acc_init, fn x, acc ->
+      newval = x + acc.sum
+
+      if newval in acc.found do
+        IO.puts("repeated frequency found: #{newval}")
+        exit(0)
+      end
+
+      %{found: [newval | acc.found], sum: newval}
+    end)
+  end
+end
+
+numlist = Day1.get_numlist()
+IO.puts(Enum.sum(numlist))
+Day1.find_first_repeat(numlist)