There is such a function:

function isTriangle(a,b,c) { for(var i = 0; i < arguments.length; i++) { if (arguments[i] == 0) { return false } for(var k = 0; k < arguments.length; k++) { var sum = 0; for(var m = 0; m < arguments.length; m++) { sum += arguments[m]; } sum = sum - arguments[i]; if (arguments[i] > sum) { return false } } } return true; } 

It takes three parameters, returns true if it is possible to build a triangle with such sides, and returns false if not.

I checked the function, it works well, but some condition of the task is apparently not met and the task does not skip.

Conditions:

Implement a method that accepts 3 integer values ​​a, b, c. It can be used to make it so that it can be built up.

(In this case, all triangles must have greater than 0 to be accepted)

.

What am I doing wrong? Task with codewars.

  • Why use arguments if the parameters are explicitly specified? The code looks as if taken from somewhere, and not self-written. - Adokenai
  • @Adokenai, and then how to iterate through them cyclically? The code is self-written, why should I take someone else's code? - uzi_no_uzi
  • I did not understand why cycles. Especially the most internal. sum = a + b + c , then one of the arguments is subtracted from the sum and a comparison is made. That is, sum = b + c compared with a . What prevents to immediately compare a> b + c? And so all sides. Even checking for zero is not necessary. - Adokenai
  • @Adokenai, Yes, maybe the most internal and superfluous, but your comparison will not work. Because I need to compare not only the first argument with all the others, but all in turn. - uzi_no_uzi
  • existence check how is done? According to the algorithm, I see that each of the lengths of the sides of the triangle must be less than or equal to the sum of the lengths of the two others. And what does the cycle with index k do? - Adokenai

1 answer 1

You need to check that none of the parties are zero, and that the sum of the two smaller parties is greater than the largest of the parties. For example, a triangle with sides 1, 2, 3 cannot exist, it will be a line. Your option returns tru

 isTriangle(1,2,3) // true (не верно) 

My decision:

 const isTriangle = (...args) => { // Ищем ноль if (args.some(n => n <= 0)) { return false; } // Сортируем по убыванию const [a, b, c] = args.sort((x, y) => y - x); // Сравнение return a > b + c; } 
  • In principle, my solution also works, but I had to fix it a little bit, not>, but> = - uzi_no_uzi