Read coordinates of 4 points. Do they make a square?

algorithm, c++

Solution

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 rhombus

The other two should be equal between themselves (call their length `y`). this guarantees a rectangle

Put a rhombus and a rectangle together and BAM! - square.

Problem

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; } ```

Original source