Skip to content

Instantly share code, notes, and snippets.

@nickangtc
Last active March 21, 2022 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickangtc/a467cd5de1a8fe08becfeb3f434886d1 to your computer and use it in GitHub Desktop.
Save nickangtc/a467cd5de1a8fe08becfeb3f434886d1 to your computer and use it in GitHub Desktop.
an example of beautiful ruby code used to validate a triangle as part of ruby koans exercise
# exercise is from http://rubykoans.com/ - a great way to learn ruby!
#! my not so succinct but works solution
def triangle(a, b, c)
validate_triangle(a, b, c)
if a == b && b == c
:equilateral
elsif a != b && b != c && c != a
:scalene
else
:isosceles
end
end
def validate_triangle(a, b, c)
raise TriangleError, "No such thing as negative or 0-length sides in a triangle" if a <= 0 || b <= 0 || c <= 0
raise TriangleError, "Incomplete triangle because the sides cannot touch and close up" if a + b <= c || a + c <= b || b + c <= a
end
# ===
# Josh's beautiful solution taken from https://stackoverflow.com/a/14445542/6463816
# ===
def triangle(a, b, c)
[a, b, c].permutation do |sides|
raise TriangleError unless sides[0] + sides[1] > sides[2]
end
case [a,b,c].uniq.size
when 3; :scalene
when 2; :isosceles
when 1; :equilateral
end
end
class TriangleError < StandardError
end
@nickangtc
Copy link
Author

nickangtc commented Mar 4, 2022

[].permutation is so easy to understand as a human! line 24

[].uniq.size and when N express the thing I'm trying to do in the form closest to how I think about it in my human mind. line 27

@psychoslave
Copy link

psychoslave commented Mar 21, 2022

Rather than sides[0] + sides[1] > sides[2], what about sides[0..1].sum > sides[2]?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment