-
-
Save danneu/1126423 to your computer and use it in GitHub Desktop.
def triangle(a, b, c) | |
raise TriangleError if a<=0 or b<=0 or c<=0 | |
raise TriangleError if a+b<=c or b+c<=a or a+c<=b | |
return :equilateral if a==b and a==c | |
return :isosceles if a==b or b==c or a==c | |
:scalene | |
end |
I threw the arguments into an array to use the "uniq" method in helping find how many unique sides.
sides = []
sides << a << b << c
sorted_sides = sides.sort
unique_sides = sides.uniq.length
raise TriangleError unless sorted_sides.first > 0
raise TriangleError unless sorted_sides.first + sorted_sides.fetch(1) > sorted_sides.last
return :equilateral if unique_sides == 1
return :isosceles if unique_sides == 2
return :scalene
Cool. My effort to condense your solution:
def triangle(a, b,c)
(a, b, c), uniq_sides = [a, b, c].sort, [a, b, c].uniq.size
raise TriangleError unless a > 0 and a + b > c
return :equilateral if uniq_sides == 1
return :isosceles if uniq_sides == 2
:scalene
end
I didn't like repeating [a, b, c]
and the only one-liner idea I had was:
a, b, c, uniq_sides = [a, b, c].sort.tap { |sides| sides << sides.uniq.size }
:/
Even better:
def triangle(a, b, c)
a, b, c = sides = [a, b, c].sort
raise TriangleError unless a > 0 and a + b > c
{1 => :equilateral, 2 => :isosceles, 3 => :scalene}[sides.uniq.size]
end
Or even:
def triangle(a, b, c)
a, b, c = sides = [a, b, c].sort
raise TriangleError unless a > 0 and a + b > c
[nil, :equilateral, :isosceles, :scalene][sides.uniq.size]
end
We're really streamlining this little chunk of code. :)
Nice. I get hung up on a tree instead of seeing the forest of refactoring.
I got rid of the nil
, but at this rate we might as well rename sides
to x
. 😔
def triangle(a, b, c)
a, b, c = sides = [a, b, c].sort
raise TriangleError unless a > 0 and a + b > c
[:scalene, :isosceles, :equilateral][-sides.uniq.size]
end
Until next time, team fistbump. 👊
Using a negative index – clever!
Dan & David,
Hi. I'm Rolando. I'm a student at Flatiron School in NYC, and this exchange was super helpful in helping me figure a solution out.
Just wanted to say thanks!
Thanks for all of you guys
Nice, that's smart.