'Ruby -If-Else Statement (Triangle Test)

The question is Create a function that takes three numbers as input and returns true or false depending on whether those three numbers can form a triangle. Three numbers can form a triangle if the sum of any two sides is greater than the third side.

my answer is:

def is_triangle(a,b,c)

  if a+b > c
    return true
  elsif a+c>b
    return true
  elsif b+c>a
    return true
  else
    return false
  end
end

the thing is: my supposed false return keeps returning true. please help!



Solution 1:[1]

This logic should work for finding your triangle

def is_triangle?(a,b,c)
  sorted = [a,b,c].sort
  greatest_side = sorted.pop
  greatest_side < sorted.sum
end

Solution 2:[2]

Yet another approach:

def is_triangle?(a,b,c)
  [a,b,c].max < [a,b,c].sum/2.0
end

Or for Ruby outside of Rails:

def is_triangle?(a,b,c)
  [a,b,c].max < [a,b,c].inject(:+)/2.0
end

Solution 3:[3]

Your problem is that unless all 3 numbers are 0 one of your ifs will always be true. What you want is something more like

def is_triangle(a,b,c)
  a + b > c && a + c > b && b + c > a
end
is_triangle(3,6,8) #=> true
is_triangle(3,6,80) #=> false

Solution 4:[4]

Nothing you pass into this is going to return false. Your method is wrong.

You can tell if three sides make a triangle by finding the longest side and then adding the remaining two sides. If they are greater than the longest side, then the sides can make a traingle.

Solution 5:[5]

I suggest if you are sure your logic is correct change the method to

def is_triangle?(a, b, c)
   a+b > c or b+c > a or c+a > b
end

But according to me it is not so the method should be

def is_triangle?(a, b, c)
   a+b>c and b+c>a and c+a>b
end

Some points to note about ruby conventions:

  1. Method which returns boolean ends with '?'
  2. A ruby method returns the last evaluated expression, so writing return is redundant here.

Solution 6:[6]

puts " enter a, b and c values"

a=gets.to_i
b=gets.to_i
c=gets.to_i

  if a+b > c    
   print true
  elsif a+c>b  
    print true
  elsif b+c>a
    print true
  else
   print false
 end

you can also use this code too.. this is much easy

Solution 7:[7]

This is also a solution to this problem :

if 2*[a,b,c].max < a + b + c
    true
else
    false
end

There are a variety of different inequalities theoretically possible:

http://en.wikipedia.org/wiki/Triangle_inequality

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jhiro009
Solution 3 Michael Kohl
Solution 4 Snukus
Solution 5 rubish
Solution 6 Jaba Jawahar
Solution 7 Kai Durai