Created
October 26, 2019 02:34
-
-
Save sushant12/1d3cfe57d2a7ee1384c2c3deaff66a76 to your computer and use it in GitHub Desktop.
check for positive happy number in ruby
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
# 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 |
.digits
is not very performant :) @veekram
https://stackoverflow.com/questions/47953598/rubys-digits-method-performance
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.