Will Clausen's Website

Categories
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++.

The task:

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[4]);

// 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[4])
{
	// First find the distances
	double dist12 = dist(coordinates[1], coordinates[2]);
	double dist34 = dist(coordinates[3], coordinates[4]);

	if (dist12 != dist34) return false;

	double dist13 = dist(coordinates[1], coordinates[3]);
	double dist24 = dist(coordinates[2], coordinates[4]);

	if (dist13 != dist24) return false;

	double dist14 = dist(coordinates[1], coordinates[4]);
	double dist23 = dist(coordinates[2], coordinates[3]);

	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.

Leave a Reply

Your email address will not be published. Required fields are marked *