Reputation: 3390
So I have this spec I'm trying to solve for (I did not write the spec)...
it "returns false if any of the arguments are 0" do
# [0, 1, 1].permutation(3) returns all permutations of [0, 1, 1]
length = rand(0.01..100.0)
[0, length, length].permutation(3).all? { |(a,b,c)| valid_triangle?(a,b,c) }.should be_false
end
Here is my code
def valid_triangle?(a, b, c)
#A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2.
if a > 0 && b > 0 && c > 0
one = a**2
two = b**2
three = c**2
if one+two=three
return "true"
else
return "false"
end
else
return "false"
end
end
How can I pass my spec? What am I missing?
Upvotes: 1
Views: 198
Reputation: 110675
The main problem is that when the test permutes the values of a
, b
and c
, your method is not always checking that it is the square of the hypotenuse that equals the sum of the squares of the other two sides. For example, if a=3
, b=4
and c=5
, one of your tests will be 4*4 + 5*5 == 3*3
. You need to sort a
, b
and c
before checking the sum of squares, which is a good idea anyway, since the position of the hypotenuse among the parameters is not guaranteed. You could also simplify your code somewhat. Here's one way you could write it:
TOLERANCE = 0.01
def right_triangle?(a, b, c)
return false if a == 0 || b == 0 || c == 0
a, b, c = [a,b,c].sort
(a**2 + b**2 - c**2).abs < TOLERANCE
end
length = rand(0.01..100.0)
[0.0, length, length].permutation(3).all? { |(a,b,c)| right_triangle?(a,b,c)}
#=> false
[3,4,5].permutation(3).all? { |(a,b,c)| right_triangle?(a,b,c) }
#=> true
Since you are dealing with floats, you need to establish some level of tolerance when comparing values for equality. I've used an arbitrary fixed amount (0.01
) for demonstration purposes.
Upvotes: 3
Reputation: 37409
You are returning "false"
and "true"
instead of false
and true
, also you check that one+two=three
, when you should check one+two==three
(an equals check, not an assignment)
def valid_triangle?(a, b, c)
#A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2.
if a > 0 && b > 0 && c > 0
one = a**2
two = b**2
three = c**2
if one+two == three
return true
else
return false
end
else
return false
end
end
Upvotes: 2