-
-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathcountTriangles.js
More file actions
33 lines (27 loc) · 926 Bytes
/
countTriangles.js
File metadata and controls
33 lines (27 loc) · 926 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function countTriangles(numbers) {
numbers.sort((a, b) => a - b);
const length = numbers.length;
let count = 0;
for(let i = 0; i < length-2; i++) {
let k = i + 2;
for(let j = i + 1; j < length-1; j++) {
while(k < length && numbers[i] + numbers[j] > numbers[k]) {
k++;
}
count += k-j-1;
}
}
return count;
}
// Examples
const examples = [
{ input: [10, 2, 5, 1, 8, 12], expected: 4 },
{ input: [4, 6, 3, 7], expected: 3 },
{ input: [1, 1, 1, 1], expected: 4 },
{ input: [5, 10, 12, 15], expected: 3 },
{ input: [1, 2, 3], expected: 0 } // Cannot form any triangle
];
examples.forEach(({ input, expected }, idx) => {
const result = countTriangles([...input]); // copy to preserve original
console.log(`Example ${idx + 1}: Input = [${input}] → Count = ${result} | Expected = ${expected}`);
});