Advertisement
Guest User

Happy Numbers

a guest
Mar 30th, 2015
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.35 KB | None | 0 0
  1. class Fixnum
  2.     def happy?
  3.         n = self
  4.         [1, 7].include? Enumerator.new {|y|
  5.             loop {
  6.                 y << (n = n.to_s.chars.map {|x| x.to_i ** 2}.reduce(:+))
  7.             }
  8.         }.lazy.select{|y| y < 10}.take(1).first
  9.     end
  10. end
  11.  
  12.  
  13. raise "Errado" unless [1, 10, 100, 130, 97, 7, 1112].collect(&:happy?).all?
  14. raise "Errado" unless ![2, 3, 4, 5, 6, 8, 8].collect(&:happy?).any?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement