Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,104 questions

40,777 answers

573 users

How to count the number of possible triangles from a given array in JavaScript

1 Answer

0 votes
// Triangle = the sum of any two values (sides) > than the third value (third side)
 
// A + B > C
// B + C > A
// C + A > B

function CountTriangles(arr) {
    const size = arr.length;
    let count = 0;
     
    for (let i = 0; i < size; i++) {
        for (let j = i + 1; j < size; j++) {
            for (let k = j + 1; k < size; k++) {
                if (arr[i] + arr[j] > arr[k] && 
                    arr[i] + arr[k] > arr[j] && 
                    arr[k] + arr[j] > arr[i]) {
                    count++;
                    console.log(arr[i] + " + " + arr[j] + " > " + arr[k] + " | " +
                                arr[i] + " + " + arr[k] + " > " + arr[j] + " | " + 
                                arr[k] + " + " + arr[j] + " > " + arr[i]);
                }
            }
        }
    }
    return count;
}
 
const arr = [120, 80, 13, 16, 9, 14, 19];
 
const total_triangles = CountTriangles(arr);
 
console.log("Total triangles : " + total_triangles);
 
 
 
 
 
 
/*
run:
 
"13 + 16 &gt; 9 | 13 + 9 &gt; 16 | 9 + 16 &gt; 13"
"13 + 16 &gt; 14 | 13 + 14 &gt; 16 | 14 + 16 &gt; 13"
"13 + 16 &gt; 19 | 13 + 19 &gt; 16 | 19 + 16 &gt; 13"
"13 + 9 &gt; 14 | 13 + 14 &gt; 9 | 14 + 9 &gt; 13"
"13 + 9 &gt; 19 | 13 + 19 &gt; 9 | 19 + 9 &gt; 13"
"13 + 14 &gt; 19 | 13 + 19 &gt; 14 | 19 + 14 &gt; 13"
"16 + 9 &gt; 14 | 16 + 14 &gt; 9 | 14 + 9 &gt; 16"
"16 + 9 &gt; 19 | 16 + 19 &gt; 9 | 19 + 9 &gt; 16"
"16 + 14 &gt; 19 | 16 + 19 &gt; 14 | 19 + 14 &gt; 16"
"9 + 14 &gt; 19 | 9 + 19 &gt; 14 | 19 + 14 &gt; 9"
"Total triangles : 10"
 
*/

 





answered Apr 15, 2023 by avibootz
edited Apr 15, 2023 by avibootz
...