WCW

# Solution: Four Points Determine a Square, Jan. 2, 2013

Here is my solution to the Programming Praxis exercise from Jan. 2, 2013. The solution is written in C++.

Your task is to write a function that determines if four input points determine a square.

My solution:

```
// Author: William Clausen
//
// Date: 1/2/13
//
// Programming Praxis Problem for January 2, 2013: Four points
// determine a square. Write a progam to determine if four points
// make up a square in the x-y plane.

#include <utility>
#include <cmath>
#include <iostream>
#include <algorithm>

using namespace std;

double dist(pair <double, double> point1, pair <double, double> point2);

bool isSquare(pair <double, double> coordinates);

// Four points determine a sqaure if picking any pair of points
// are the same distance apart...and two of the three distances are
// equal
bool isSquare(pair<double, double> coordinates)
{
// First find the distances
double dist12 = dist(coordinates, coordinates);
double dist34 = dist(coordinates, coordinates);

if (dist12 != dist34) return false;

double dist13 = dist(coordinates, coordinates);
double dist24 = dist(coordinates, coordinates);

if (dist13 != dist24) return false;

double dist14 = dist(coordinates, coordinates);
double dist23 = dist(coordinates, coordinates);

if (dist14 != dist23) return false;

// If the above checks pass, find the max distance and make sure
// the two smaller distances are equal.
double maxDist = max(dist12, max(dist13, dist14));

if (maxDist == dist12) {
return dist13 == dist14;
} else if (maxDist == dist13) {
return dist12 == dist14;
} else {
return dist12 == dist13;
}
}

// Helper function to determine the distance between to points in an
// x-y plane.
double dist(pair<double, double> point1, pair<double, double> point2)
{
// The distance between 2 points can be found using the pythagorean
// theorem.
double xDiff = point2.first - point1.first;
double yDiff = point2.second - point1.second;

double diffSquared = pow(xDiff, 2) + pow(yDiff, 2);

return sqrt(diffSquared);
}

// This code produced the correct output for tests provided in the
// problem statement.

```