In a 2d plane, four points are given. This algorithm will check whether four points are forming a square or not.
Checking for a square we have to match these conditions −
- All four sides formed by given points are same.
- All two connecting sides are right-angled.
Input and Output
Input:
Four points {(20, 10), (10, 20), (20, 20), (10, 10)}
Output:
Points are forming a square.Algorithm
isFormingSquare(p1, p2, p3, p4)
In this procedure, we will use a method squareDist(p1, p2), it will return squared distance of two given points.
Input: Four points.
Output: True when given points are forming a square.
Begin dist12 := squareDist(p1, p2) dist13 := squareDist(p1, p3) dist14 := squareDist(p1, p4) if dist12 = dist13 and 2*dist12 = dist14, then dist := squareDist(p2, p4) return true when dist = squareDist(p3, p4) and dist = dist12 if dist13 = dist14 and 2*dist13 = dist12, then dist := squareDist(p2, p3) return true when dist = squareDist(p2, p4) and dist = dist13 if dist12 = dist14 and 2*dist12 = dist13, then dist := squareDist(p2, p3) return true when dist = squareDist(p3, p4) and dist = dist12 return false End
Example
#include<iostream>
using namespace std;
struct Point {
int x, y;
};
int squareDist(Point p, Point q) {
return (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 not
int dist12 = squareDist(p1, p2); // distance from p1 to p2
int dist13 = squareDist(p1, p3); // distance from p1 to p3
int dist14 = 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 (dist12 == dist13 && 2*dist12 == dist14) {
int dist = squareDist(p2, p4);
return (dist == squareDist(p3, p4) && dist == dist12);
}
//same condition for all other combinations
if (dist13 == dist14 && 2*dist13 == dist12) {
int dist = squareDist(p2, p3);
return (dist == squareDist(p2, p4) && dist == dist13);
}
if (dist12 == dist14 && 2*dist12 == dist13) {
int dist = squareDist(p2, p3);
return (dist == squareDist(p3, p4) && dist == dist12);
}
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.";
else
cout << "Points are not forming a square";
}Output
Points are forming a square.