How to check if four points form a square
A square is a four-sided figure with a 90-degree angle formed at each vertex, with all sides equal. In a 2d plane, there are four random points, and we need to check whether these points make a square.
Understand the problem
Assume that we get four coordinates of points in the 2d plane. To check for the squareness of a given point, we must verify the following.
Each of the four sides created by points is identical.
Any two sides form an angle of 90 degrees.
Verify that both diagonals have the same length.
Now to know the distance between 2 points, we have the following formula:
Solution
The objective is to find the distance between any point and the remaining points. Let the selected point be "p". To make a square, the distance between two points from "p" must be the same. Denote this distance as d. The distance between two points must be distinct from d and equal to
Additionally, we must ensure that q is at the same distance from two other points and that this distance equals d.
Implementation
The implementation of the solution explained above in C++ is given below:
#include<iostream>using namespace std;struct Point {int x, y;};int squareDist(Point p, Point q) { //square distance formulareturn (p.x - q.x)*(p.x - q.x) + (p.y - q.y)*(p.y - q.y);}bool isSquare(Point p1, Point p2, Point p3, Point p4) { //check four points are forming square or notint dist2 = squareDist(p1, p2); // distance from p1 to p2int dist3 = squareDist(p1, p3); // distance from p1 to p3int dist4 = squareDist(p1, p4); // distance from p1 to p4//when length of p1-p2 and p1-p3 are same, and square of (p1-p4) = 2*(p1-p2)if (dist2 == dist3 && 2*dist2 == dist4) {int dist = squareDist(p2, p4);return (dist == squareDist(p3, p4) && dist == dist2);}//same condition for all other combinationsif (dist3 == dist4 && 2*dist3 == dist2) {int dist = squareDist(p2, p3);return (dist == squareDist(p2, p4) && dist == dist3);}if (dist2 == dist4 && 2*dist2 == dist3) {int dist = squareDist(p2, p3);return (dist == squareDist(p3, p4) && dist == dist2);}return false;}int main() {Point p1 = {20, 10}, p2 = {10, 20}, p3 = {20, 20}, p4 = {10, 10};if(isSquare(p1, p2, p3, p4))cout << "Points are forming a square.";elsecout << "Points are not forming a square";}
Code explanation
Lines 4–9: We create the struct
Pointfor the 2d coordinates in thex,yplane. We define thesquareDist()formula to calculate the distance between two points.Lines 12–15: We define
isSquare()function to check whether given points make a square or not. We initialize three variables to calculate the distance ofp1fromp2,p3andp4.Lines 17–21: For
dist2, we check if it is equal to thedist3and two times ofdist4. We returntrueif thedistis equal to thedist3and thesquareDist()of other points.Lines 23–33: We define the same condition for the remaining points.
Free Resources