Skip to content

Instantly share code, notes, and snippets.

@norbajunior
Created March 30, 2015 21:13
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 norbajunior/2a230ae65800e08de60f to your computer and use it in GitHub Desktop.
Save norbajunior/2a230ae65800e08de60f to your computer and use it in GitHub Desktop.
class Integer
@@results = []
def happy?
value = digits_square_sum
return false if @@results.include?(value)
if value == 1
@@results = []
return true
end
@@results << value
value.happy?
end
private
def digits_square_sum
self.to_s.chars.map { |num| num.to_i ** 2 }.reduce(:+)
end
end
puts 19.happy? # => true
1.upto(30) do |n|
puts "#{n} is #{n.happy? ? 'happy' : 'unhappy'}"
end
# 1 is happy
# 2 is unhappy
# 3 is unhappy
# 4 is unhappy
# 5 is unhappy
# 6 is unhappy
# 7 is happy
# 8 is unhappy
# 9 is unhappy
# 10 is happy
# 11 is unhappy
# 12 is unhappy
# 13 is happy
# 14 is unhappy
# 15 is unhappy
# 16 is unhappy
# 17 is unhappy
# 18 is unhappy
# 19 is happy
# 20 is unhappy
# 21 is unhappy
# 22 is unhappy
# 23 is happy
# 24 is unhappy
# 25 is unhappy
# 26 is unhappy
# 27 is unhappy
# 28 is happy
# 29 is unhappy
# 30 is unhappy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment