Skip to content

Instantly share code, notes, and snippets.

@thiagoa
Last active July 13, 2017 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagoa/92a78a39528cd5b967472fb4a2f1f22d to your computer and use it in GitHub Desktop.
Save thiagoa/92a78a39528cd5b967472fb4a2f1f22d to your computer and use it in GitHub Desktop.
defmodule Collatz do
def call(n, cache), do: call(n, 0, cache)
def call(1, length, _), do: length + 1
def call(n, length, cache), do: get(n, length, cache, cache[n])
defp get(n, length, cache, nil), do: call(next(n), length, cache) + 1
defp get(_, _, _, value), do: value
defp next(n) when rem(n, 2) == 0, do: div(n, 2)
defp next(n) when rem(n, 2) == 1, do: n * 3 + 1
end
defmodule Main do
def run(min, limit), do: run(min, %{}, limit, {0, 0})
def run(n, _, limit, result) when n > limit, do: result
def run(n, cache, limit, result), do: cache_and_loop(n, cache, limit, result, Collatz.call(n, cache))
def cache_and_loop(n, cache, limit, result, length) do
run(n + 1, Map.put_new(cache, n, length), limit, max(n, length, result))
end
defp max(n, length, {_, max_length}) when length > max_length, do: {n, length}
defp max(_, _, result), do: result
end
IO.inspect Main.run(1, 1_000_000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment