DEV Community

Discussion on: Write a script to find "Happy Numbers"

Collapse
 
rpalo profile image
Ryan Palo • Edited

How does this look? I initially had happy memoizing previous numbers, but it seemed like it ran fast enough without it, and the memoizing cluttered things up.

Also, I didn't know about the digits method until now! :)

def happy_numbers
  Enumerator.new do |out|
    1.step do |i|
      out << i if happy?(i)
    end
  end
end

def happy?(num)
  already_seen = []
  current_step = num
  until current_step == 1 || already_seen.include?(current_step)
    already_seen << current_step
    current_step = square_digit_sum(current_step)
  end
  current_step == 1
end

def square_digit_sum(num)
  num
    .digits
    .map { |x| x**2 }
    .sum
end

emitter = happy_numbers
puts emitter.first(10)

# => 1, 7, 10, 13, 19, 23, 28, 31, 32, 44