Computer >> Computer tutorials >  >> Programming >> Javascript

Counting number of triangle sides in an array in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.

The task of our function is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.

For example, if the input to the function is −

const arr = [2, 2, 3, 4];

Then the output should be −

const output = 3;

Output Explanation

Valid combinations are:

2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3

Example

Following is the code −

const arr = [2, 2, 3, 4];
const countTriangle = (arr = []) => {
   arr.sort((a, b) => a - b)
   let k = 2
   let count = 0
   for (let i = 0; i < arr.length - 2; i++) {
      for (let j = i + 1; j < arr.length - 1; j++) {
         k = j + 1
         while (arr[k] < arr[i] + arr[j]) {
            k += 1
         }
         count += k - j - 1
      }
   }
   return count
};
console.log(countTriangle(arr));

Output

Following is the console output −

3