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
Validating a square in a 2-D plane in JavaScript
We are required to write a JavaScript function that takes in four arguments. The four arguments will all be arrays of exactly two numbers representing the coordinates of four vertices of a quadrilateral or any figure (closed or unclosed) on a plane.
The task of our function is to determine whether or not the four vertices form a square.
If they do form a square, we should return true, false otherwise.
Understanding the Problem
A square has specific properties:
- All four sides are equal in length
- All four angles are 90 degrees
- The two diagonals are equal and longer than the sides
For example, if the input coordinates are:
const c1 = [1, 0]; const c2 = [-1, 0]; const c3 = [0, 1]; const c4 = [0, -1];
Then the output should be true because these coordinates do form a square with area 2 unit sq.
Algorithm Approach
Our approach calculates all pairwise distances between the four points. In a square, we should have exactly two unique distances:
- 4 equal side lengths
- 2 equal diagonal lengths (longer than sides)
Example Implementation
const c1 = [1, 0];
const c2 = [-1, 0];
const c3 = [0, 1];
const c4 = [0, -1];
const validSquare = (c1, c2, c3, c4) => {
const dist = (c1, c2) => Math.sqrt(Math.pow(c1[0] - c2[0], 2) + Math.pow(c1[1] - c2[1], 2));
const points = [c1, c2, c3, c4];
let lens = new Set();
for (let i = 0; i < points.length; i++) {
for (let j = i + 1; j < points.length; j++) {
// Check for duplicate points
if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) {
return false;
}
let dis = dist(points[i], points[j]);
lens.add(dis);
}
}
// A square should have exactly 2 unique distances
return lens.size === 2;
};
console.log(validSquare(c1, c2, c3, c4));
true
Testing with Different Cases
// Test case 1: Valid square
const square1 = validSquare([0, 0], [1, 0], [1, 1], [0, 1]);
console.log("Square 1:", square1);
// Test case 2: Rectangle (not square)
const rectangle = validSquare([0, 0], [2, 0], [2, 1], [0, 1]);
console.log("Rectangle:", rectangle);
// Test case 3: Random quadrilateral
const quad = validSquare([0, 0], [1, 0], [2, 1], [0, 2]);
console.log("Quadrilateral:", quad);
Square 1: true Rectangle: false Quadrilateral: false
How It Works
The function works by:
- Calculating the distance between every pair of points (6 total distances)
- Storing unique distances in a Set
- Checking for duplicate points (invalid square)
- Verifying that exactly 2 unique distances exist (4 sides + 2 diagonals)
Conclusion
This approach efficiently validates squares by leveraging the geometric property that squares have exactly two unique distances. The algorithm handles edge cases like duplicate points and works for any orientation of the square.
