Algorithm to Count the Number of Possible Triangles

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

  • To simplify the computations, sort the array ascending.
  • Set up a variable to hold the number of triangles.
  • Choose one side length to serve as a fixed base by iterating across the array.
  • To identify pairs of sides (a, b) that meet the triangle inequality condition: a + b > base, use the two-pointer strategy.
  • Increment the count of triangles with each valid combination of sides found.
  • Continue the process until all possible combinations are checked.

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

Javascript




// 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

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.

Similar Reads

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:...

Algorithm to Count the Number of Possible Triangles

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

Complexity Analysis:

...