[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: [QUIZ SOLUTION] Happy Numbers (#93

email55555 email55555

9/4/2006 3:03:00 AM

Here is my simple solution, not thread safe, not optimize for finding
happiest number between 2 numbers.

happy? method returns false if the number is unhappy or happy list if
the number is happy.

class Integer
def digits(base = 10)
return [self] if self < base
self.divmod(base).inject { |div, mod| div.digits(base) << mod }
end

def happy?(base = 10)
@@happy_list = []
_happy?(base) ? @@happy_list : false
end

protected

def _happy?(base)
return false if @@happy_list.include?(self)
@@happy_list << self
return true if self == 1
self.digits(base).inject(0) { |n, d| n + d*d }._happy?(base)
end
end


# some simple tests
if __FILE__ == $0
p 7.happy?
p 37.happy?
p 25.happy?(2) # base 2 is "happy base" all numbers(>0) on base 2
are happies.
p 4394.happy?(16)
p 367.happy?(100)
end