Check if given four points form a square or not?
·1 min
Problem Solving
Read the problem statement here:
GeeksForGeeks: https://practice.geeksforgeeks.org/problems/is-square/0
C++ code:
#include<bits/stdc++.h> using namespace std;
typedef struct{ int x, y; }Point;
bool isSquare(Point p1, Point p2, Point p3, Point p4); int dist(Point m, Point n);
int main(void){ int t; Point p1, p2, p3, p4;
scanf("%d", &t);
while(t--){
scanf("%d %d", &p1.x, &p1.y);
scanf("%d %d", &p2.x, &p2.y);
scanf("%d %d", &p3.x, &p3.y);
scanf("%d %d", &p4.x, &p4.y);
if(isSquare(p1, p2, p3, p4)){
cout<<"Yes"<<endl;
}else{
cout<<"No"<<endl;
}
}
}
bool isSquare(Point p1, Point p2, Point p3, Point p4){ //distance of all four sides int d1 = dist(p1, p2); int d2 = dist(p4, p3); int d3 = dist(p1, p4); int d4 = dist(p2, p3); //distance of the diagonals int dg1 = dist(p1, p3); int dg2 = dist(p2, p4);
//distance cannot be zero or negative
if(d1 <= 0 || d2 <= 0 || d3 <= 0 || d4 <= 0 || dg1 <= 0 || dg2 <= 0)
return false;
if(d1 == d2){
if(d3 == d4){
if(dg1 == dg2){
return true;
}
}
}
return false;
}
int dist(Point m, Point n){ return ( sqrt( pow((n.x - m.x), 2) + pow((n.y - m.y), 2) ) ); }