From 50fd8d6dd2013ac9d4d600890ebd68839bf20f96 Mon Sep 17 00:00:00 2001 From: Duff OMelia Date: Mon, 3 Dec 2018 07:53:04 -0500 Subject: [PATCH] Use Stream.cycle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pretty neat. Learned from José's twitch. --- .gitignore | 1 + lib/advent_2018/day_1_b.ex | 31 +++++++++---------------------- 2 files changed, 10 insertions(+), 22 deletions(-) diff --git a/.gitignore b/.gitignore index 05df5c5..00f1c89 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,4 @@ erl_crash.dump # Ignore package tarball (built via "mix hex.build"). advent_2018-*.tar +_scratch diff --git a/lib/advent_2018/day_1_b.ex b/lib/advent_2018/day_1_b.ex index cbadff4..1cb8308 100644 --- a/lib/advent_2018/day_1_b.ex +++ b/lib/advent_2018/day_1_b.ex @@ -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