# Re: Happy Numbers (#93)

**URL:** <https://www.ruby-forum.com/t/re-happy-numbers-93/67761>\
**Category:** Ruby\
**Created:** [September 6, 2006, 5:06pm UTC](https://www.ruby-forum.com/t/re-happy-numbers-93/67761 "2006-09-06T17:06:15Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![davidtl](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/35a633/32.png) [@davidtl](https://www.ruby-forum.com/u/davidtl)\
**Post date:** [September 6, 2006, 5:06pm UTC](https://www.ruby-forum.com/t/re-happy-numbers-93/67761/1 "2006-09-06T17:06:15Z")

</div>

Modified from Simon’s solution.  
This one has 3 lines longer, but it takes ~ half time compare to the  
origin  
for finding the happiest between 1 and 100000.

* * *

happy = Hash.new do |h, k|  
digits = k.to\_s.split(’’)  
digits\_sorted = digits.sort  
next h[k] = h[digits\_sorted.join.to\_i] if digits != digits\_sorted  
sum = digits.inject(0) {|s, i| s + i.to\_i \* i.to\_i}  
sum != 1 ? (h[k] = 0) : (next h[k] = 1)  
h[k] = (h[sum].nonzero? || -1) + 1  
end

puts (1…100000).max {|a, b| happy[a] \<=\> happy[b]}
