require 'set' 

@seen_numbers = Set.new
@happy_numbers = Set.new

def happy?(n)
  return true if n == 1 
  return @happy_numbers.include?(n) if @seen_numbers.include?(n) 

  @seen_numbers << n
  digit_squared_sum = n.to_s.each_char.inject(0) { |sum, c| sum + c.to_i**2 } 

  if happy?(digit_squared_sum)
    @happy_numbers << n
    true 
  else
    false 
  end
end