Skip to content

Instantly share code, notes, and snippets.

@sushant12
Created October 26, 2019 02:34
Show Gist options
  • Save sushant12/1d3cfe57d2a7ee1384c2c3deaff66a76 to your computer and use it in GitHub Desktop.
Save sushant12/1d3cfe57d2a7ee1384c2c3deaff66a76 to your computer and use it in GitHub Desktop.
check for positive happy number in ruby
# a tail call optimized ruby script to find happy number
def happy_number?(num, seen_number = {})
# store num in hash for quick lookup
seen_number[num] = num
total = num
.to_s
.chars
.reduce(0) { |acc, digit| acc + digit.to_i ** 2 }
return true if total == 1
return false if seen_number[total]
happy_number?(total, seen_number)
end
# test cases
puts happy_number?(6) == false
puts happy_number?(7) == true
@veekram
Copy link

veekram commented Oct 28, 2019

This can be:
total = num .to_s .chars .reduce(0) { |acc, digit| acc + digit.to_i ** 2 }

total = num.digits.reduce(0) { |acc, digit| acc + digit ** 2 }

This way we don't need to covert to_s and then to_i again.

@sushant12
Copy link
Author

sushant12 commented Oct 28, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment