Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Valid triangle edges - JavaScript
In geometry, three lines can form a triangle only if they satisfy the triangle inequality theorem: the sum of any two sides must be greater than the third side. This fundamental rule ensures that the three sides can actually connect to form a closed triangle.
For example, if three lines have lengths 4, 9, and 3, they cannot form a triangle because 4 + 3 = 7, which is less than 9. At least one side would be too long to connect with the other two.
Triangle Inequality Theorem
For sides with lengths a, b, and c to form a valid triangle, all three conditions must be true:
- a + b > c
- b + c > a
- c + a > b
JavaScript Implementation
Here's a function that checks if three given lengths can form a valid triangle:
const a = 9, b = 5, c = 3;
const isValidTriangle = (a = 1, b = 1, c = 1) => {
if (!a || !b || !c) {
return false;
}
const con1 = a + b > c;
const con2 = b + c > a;
const con3 = c + a > b;
return con1 && con2 && con3;
};
console.log(isValidTriangle(a, b, c));
false
Testing Different Cases
Let's test the function with various triangle combinations:
const isValidTriangle = (a = 1, b = 1, c = 1) => {
if (!a || !b || !c) {
return false;
}
const con1 = a + b > c;
const con2 = b + c > a;
const con3 = c + a > b;
return con1 && con2 && con3;
};
// Test cases
console.log("Valid triangles:");
console.log("3, 4, 5:", isValidTriangle(3, 4, 5)); // Right triangle
console.log("5, 5, 5:", isValidTriangle(5, 5, 5)); // Equilateral
console.log("6, 8, 10:", isValidTriangle(6, 8, 10)); // Valid triangle
console.log("\nInvalid triangles:");
console.log("1, 2, 5:", isValidTriangle(1, 2, 5)); // 1+2
Valid triangles:
3, 4, 5: true
5, 5, 5: true
6, 8, 10: true
Invalid triangles:
1, 2, 5: false
0, 4, 5: false
2, 3, 8: false
How the Function Works
The function first checks if any side has zero or negative length, returning false immediately. Then it evaluates all three triangle inequality conditions and returns true only if all are satisfied.
Conclusion
The triangle inequality theorem is essential for validating triangle sides. This JavaScript function provides a reliable way to check if three given lengths can form a valid triangle by testing all three required conditions.
