0

I'm doing a ruby kata to return an array of perfect squares given an array. A perfect square such as 4 will yield 2.0. A number that isn't perfect will be a decimal like 2.343 etc. I want to make it work so that, if the tenths place is anything other than zero, it will drop the number. Any thoughts?

I would use modulo, but I don't think there's a use for what I'm trying to do. I was wondering if there was a method other than modulo that could grab the remainder of a number for comparison. I saw the ruby docs for zero?, divmod, and a few others, but they don't do exactly what I need.

Here is my code:

def get_squares(array)
  array.to_a.drop_while do |number|
    Math.sqrt(number) #== drop if remainder is something other than .0
  end
end

get_squares((1..16))
sawa
  • 165,429
  • 45
  • 277
  • 381
Dan Rubio
  • 4,709
  • 10
  • 49
  • 106
  • 1
    Can you clarify what you mean by "if the tenths place is anything other than zero, it will drop the number"? Do you mean that, if the square root of `num` is something like `3.382247284074723...`, then keep `num`, but if it is something like `3.382247284374923...` then it is supposed to be removed from the array? – sawa Jun 09 '14 at 13:54
  • Hey @sawa. I got the answer already but what I was trying to communicate was that if the number was for example 2.0 keep it, but if it was 3.2456 from an imperfect square then it needed to be dropped. – Dan Rubio Jun 09 '14 at 14:10

1 Answers1

0

You can do:

class Float
  def is_int?
    self.to_i == self
  end
end

def get_squares(array)
  array.select { |number| Math.sqrt(number).is_int? }
end
BroiSatse
  • 44,031
  • 8
  • 61
  • 86
  • [IEEE 745](http://en.wikipedia.org/wiki/IEEE_floating_point) => `Math.sqrt(1234567890**2 - 1).is_int? == true`. Instead ot this he/she should use pure integer solution http://stackoverflow.com/questions/2489435/how-could-i-check-if-a-number-is-a-perfect-square. – Hauleth Jun 09 '14 at 14:04
  • I agree that he shouldn't calculate square roots for every number, however this is not what he asked for. – BroiSatse Jun 09 '14 at 14:12