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
Checking for convex polygon in JavaScript
A convex polygon is a polygon where all interior angles are less than 180°. In a convex polygon, all vertices point "outward" and no line segment between any two points inside the polygon extends outside the polygon.
Problem Statement
We need to write a JavaScript function that takes an array of coordinates representing vertices of a polygon. Each coordinate is an array containing two numbers [x, y] representing a point on a 2D plane. The function should return true if the polygon is convex, false otherwise.
For example, if the input is:
const arr = [[0,0],[0,1],[1,1],[1,0]];
The expected output is:
true
These points form a perfect square where all interior angles are 90°, making it convex.
Algorithm Explanation
To determine if a polygon is convex, we use the cross product method. We calculate the cross product of consecutive edge vectors. For a convex polygon, all cross products should have the same sign (all positive or all negative).
Implementation
const arr = [[0,0],[0,1],[1,1],[1,0]];
const isConvex = (arr = []) => {
const { length } = arr;
let pre = 0, curr = 0;
for (let i = 0; i 0 && pre 0))
return false;
else
pre = curr;
}
}
return true;
};
console.log(isConvex(arr));
true
Testing with Different Examples
// Test case 1: Square (convex)
const square = [[0,0],[0,2],[2,2],[2,0]];
console.log("Square:", isConvex(square));
// Test case 2: Triangle (convex)
const triangle = [[0,0],[1,2],[2,0]];
console.log("Triangle:", isConvex(triangle));
// Test case 3: Concave polygon
const concave = [[0,0],[2,0],[1,1],[2,2],[0,2]];
console.log("Concave polygon:", isConvex(concave));
function isConvex(arr = []) {
const { length } = arr;
let pre = 0, curr = 0;
for (let i = 0; i 0 && pre 0))
return false;
else
pre = curr;
}
}
return true;
}
Square: true Triangle: true Concave polygon: false
How It Works
The algorithm works by:
- Edge vectors: For each vertex, calculate vectors to the next two vertices
- Cross product: Compute the cross product of consecutive edge vectors
- Sign consistency: Check if all non-zero cross products have the same sign
- Result: If signs are consistent, the polygon is convex
Conclusion
The cross product method efficiently determines polygon convexity by checking the consistency of turn directions at each vertex. This algorithm runs in O(n) time complexity, making it suitable for real-time applications.
