# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# :equilateral if all sides are equal
# :isosceles if exactly 2 sides are equal
# :scalene if no sides are equal
#
def triangle(a, b, c)
raise TriangleError, "Wrong length" if [a,b,c].any? { |e| e <= 0 }
[a,b,c].zip([b,c,a], [c,a,b]).each do |arr|
raise TriangleError, "Too small" if arr[0] >= arr[1] + arr[2]
end
uniqe_elements = [a,b,c].uniq.length;
return :equilateral if uniqe_elements == 1
return :isosceles if uniqe_elements == 2
:scalene
end
Refactorings
No refactoring yet !
Ben Marini
October 18, 2010, October 18, 2010 15:36, permalink
class TriangleError < StandardError; end
def triangle(a, b, c)
if [a,b,c].any? { |e| e <= 0 }
raise TriangleError, "Wrong length"
end
if [ [a,b+c], [b,a+c], [c,a+b] ].any? { |(side, sum)| side >= sum }
raise TriangleError, "Too small"
end
case [a,b,c].uniq.length
when 1 then :equilateral
when 2 then :isosceles
else; :scalene
end
end
Adam
October 18, 2010, October 18, 2010 19:06, permalink
Doesn't the "Too small" check make finding scalene triangles impossible?
class TriangleError < StandardError; end
class WrongLengthError < TriangleError; end
def triangle(*sides)
raise(ArgumentError, "wrong number of arguments (#{sides.size} for 3)") if sides.size != 3
raise(WrongLengthError, "wrong length (#{sides.join(', ')}, must be all greater than zero)") if sides.any? { |side| side <= 0 }
return :equilateral if sides.uniq.size == 1
return :isosceles if sides.uniq.size == 2
return :scalene
end
This code performs triangle analyzes. I want it to look more elegant...