Skip to content

Commit

Permalink
Use Stream.cycle
Browse files Browse the repository at this point in the history
Pretty neat. Learned from José's twitch.
  • Loading branch information
duff committed Dec 3, 2018
1 parent b956d62 commit 50fd8d6
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 22 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ erl_crash.dump
# Ignore package tarball (built via "mix hex.build").
advent_2018-*.tar

_scratch
31 changes: 9 additions & 22 deletions lib/advent_2018/day_1_b.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,15 @@ defmodule Advent2018.Day1B do
def first_duplicate(input) do
input
|> as_integers()
|> do_first_duplicate()
end

defp do_first_duplicate(original_deltas) do
do_first_duplicate(original_deltas, 0, MapSet.new(), original_deltas)
end

defp do_first_duplicate([next | rest], current_frequency, past_frequencies, original_deltas) do
if MapSet.member?(past_frequencies, current_frequency) do
current_frequency
else
do_first_duplicate(
rest,
current_frequency + next,
MapSet.put(past_frequencies, current_frequency),
original_deltas
)
end
end

defp do_first_duplicate([], current_frequency, past_frequencies, original_deltas) do
do_first_duplicate(original_deltas, current_frequency, past_frequencies, original_deltas)
|> Stream.cycle()
|> Enum.reduce_while({0, MapSet.new([0])}, fn each, {current_frequency, past_frequencies} ->
new_frequency = current_frequency + each
if new_frequency in past_frequencies do
{:halt, new_frequency}
else
{:cont, {new_frequency, MapSet.put(past_frequencies, new_frequency)}}
end
end)
end

defp as_integers(input) do
Expand Down

0 comments on commit 50fd8d6

Please sign in to comment.