I calculate the distance between the points and if the distances are equal the point make a square, else no. My code works only if I read the coordinates in the following order A(x, y), B(x, y), C(x, y), D(x, y) or reverse. But if I read like this for example A(x, y), B(x, y), D(x, y), C(x, y) it won't work because the dist method will calculate the square's diagonal length. How can I solve this problem?
#include <iostream>
using namespace std;
struct {
int x;
int y;
}a[10];
int dist(int x1, int y1, int x2, int y2)
{
int c1, c2;
c1 = x2-x1;
c2 = y2-y1;
return (c1*c1)+(c2*c2);
}
int main()
{
int d1, d2, d3, d4;
for (int i=1; i<=4; i++)
{
cout << 'X' << i << '='; cin >> a[i].x;
cout << 'Y' << i << '='; cin >> a[i].y;
}
d1 = dist(a[1].x, a[1].y, a[2].x, a[2].y);
d2 = dist(a[2].x, a[2].y, a[3].x, a[3].y);
d3 = dist(a[3].x, a[3].y, a[4].x, a[4].y);
d4 = dist(a[4].x, a[4].y, a[1].x, a[1].y);
if(d1==d2 && d1==d3 && d1==d4)
cout << "Is a square";
else
cout << "Is not a square";
return 0;
}
Checking the distances is not enough, you'll need to check at least an angle, as the shape could be a rhombus.
Checking only angles is also not enough, because you could end up with a rectangle.
There are a total of 6 distances between the points. Calculate all of them. Out of those 6, four should be equal (call their length
x
). - this guarantees a rhombusThe other two should be equal between themselves (call their length
y
). this guarantees a rectanglePut a rhombus and a rectangle together and BAM! - square.
Choose one vertex of the square (without loss of generality say A) and consider this the origin. Get 3 vectors formed from the origin to each other corner (AB, AC, AD). Vectorially these are given by B-A, C-A and D-A. Calculate the inner product of each vector with the other. If the vertices form a rectangle, one inner product will be zero (the perpendicular edge vectors). If they form a square then the other 2 inner products also must be equal to each other due to the common angle of 45 degrees between them. Thus if one inner product is zero and the other 2 are equal to eachother and the 4 distances are the same you have a square.
With four points, you have a total of six distances. If you compute the distance squared (which is easier, of course), then for any pair of edges with length L1, L2, the following is true
You can create the following piece of code to implement this:
You can actually do it with only angles using inner products. Each vertex A should have two other vertices B and C such that AB and AC are at a right angle (0 inner product) as well as one vertex D such that AB and AD as well AC and AD are both at exactly 45 degrees (normalized dot product = acos(45 degrees), i.e. ~ 0.6675). If that is true for all four vertices you have a square.