Open In App

JavaScript Program to Count the Number of Possible Triangles in Array

Triangles are basic geometric figures with three sides and three angles. Finding the number of triangles that can be created from a given set of side lengths is a frequent challenge in computational programming. In this article, we’ll see how to use a JavaScript array to calculate the total number of triangles that could exist. Before we proceed, we will understand the prerequisites for a legitimate triangle and offer a methodical solution to this issue.

Conditions for a Valid Triangle

The length of any two sides added together must be more than the length of the third side in order for a triangle to be considered valid. In other words, for three side lengths a, b, and c to form a triangle, the conditions listed below must be true:



a + b > c
a + c > b
b + c > a

Algorithm to Count the Number of Possible Triangles

To count the number of possible triangles in a JavaScript array, we’ll follow these steps:

Example: This example shows the use of the above-explained approach.






// Function to Count all the
// possible number of triangle
function PossibleNumberOfTriangles(arr, n) {
  
// Initialize count variable C to 
// count the number of triangles
    let C = 0; 
  
    // The three loops will select 3
    // different values from the array
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            for (let k = j + 1; k < n; k++) {
              
                // This loop check for triangle property
                // Check Sum of two side is greater
                // than third side
                if (
                    arr[i] + arr[j] > arr[k] &&
                    arr[i] + arr[k] > arr[j] &&
                    arr[k] + arr[j] > arr[i]
                ) {
                    C++;
                }
            }
        }
    }
    return C;
}
  
// Driver Code
const arr = [2, 3, 4, 5, 8, 9];
const length = arr.length;
console.log(
    "Total number of possible triangles are: " +
    PossibleNumberOfTriangles(arr, length)
);

Output
Total number of possible triangles are: 8

Complexity Analysis:

Time Complexity: O(n3)

Explanation: The time complexity in sorting is O(n log n), Binary search O(log n) and in 3 Nested loops is O(n3).

Thus the final time complexity of the algorithm is O(n log n) + O(n log n) + O(n3) => O(n3).

Space Complexity:

The algorithm’s overall space complexity is O(n) as no extra space is required.

Optimizations Technique for Efficiency:

  1. Skip duplicate sides: The algorithm may take into account duplicate side lengths unnecessarily in the current implementation, which could result in repeated calculations. This can be avoided by skipping iterations when traversing the array and coming across equal side lengths.
  2. Exit early for sorted arrays: The process can stop early if the input array has already been sorted in ascending order since no valid triangles can be created. If the array is sorted, we may add a check at the beginning to confirm it and return 0 if it is.
  3. Use binary search: As the array is sorted, we may use a binary search to optimize the search for the third side rather than utilizing the two-pointers method. By doing this, the time complexity of looking for a valid pair (a, b) is decreased from O(n) to O(log n).

Conclusion:

Understanding the requirements for a valid triangle and putting an effective technique to use to identify all feasible side-length combinations will help you determine how many triangles are possible in a JavaScript array. We can improve efficiency and prevent unnecessary computations by optimizing the method with duplicate side skips and binary search.


Article Tags :