James Gray
9/6/2006 2:13:00 PM
On Sep 6, 2006, at 4:02 AM, Simon Kröger wrote:
> I just posted it because i didn't saw a solution using the block
> form of Hash.new yet.
My own solution, inspired by Simon's:
#!/usr/bin/env ruby -w
UNHAPPY = [0, 4, 16, 20, 37, 42, 58, 89, 145].freeze
happy = Hash.new do |found, num|
digits = num.to_s.split("").sort.delete_if { |d| d == "0" }
happiness = digits.inject(0) { |sum, d| sum + d.to_i ** 2 }
found[num] = if happiness == 1
true
elsif UNHAPPY.include? happiness
false
else
found[happiness]
end
end
(1..100_000).each { |n| p n if happy[n] }
__END__
James Edward Gray II