Created
May 6, 2015 01:30
-
-
Save gvc/439b41e8f190d361a06a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule HappyNumbers do | |
def happy?(n) do | |
do_happy?(n, []) | |
end | |
defp do_happy?(1, _sequence), do: true | |
defp do_happy?(n, sequence) do | |
if Enum.member?(sequence, n) do | |
false | |
else | |
n |> | |
digits |> | |
Enum.map(&(&1 * &1)) |> | |
Enum.sum |> | |
do_happy?([n | sequence]) | |
end | |
end | |
def digits(n) do | |
do_digits(n, []) | |
end | |
defp do_digits(n, previous_digits) when n < 10 do | |
[n | previous_digits] | |
end | |
defp do_digits(n, previous_digits) do | |
do_digits(div(n, 10), [rem(n, 10) | previous_digits]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment