Skip to content

Instantly share code, notes, and snippets.

@CallumWatkins
Last active February 18, 2017 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CallumWatkins/52fe83327a6f3df97860ea3edad7921c to your computer and use it in GitHub Desktop.
Save CallumWatkins/52fe83327a6f3df97860ea3edad7921c to your computer and use it in GitHub Desktop.
Checks whether an array of points forms a square. License: MIT
using System;
using System.Drawing;
/// <summary>
/// Checks whether an array of <see cref="Point"/> forms a square.
/// </summary>
/// <param name="points">The points to check.</param>
private static bool CheckIfPointsMakeSquare(Point[] points)
{
if (points == null) { throw new ArgumentNullException(nameof(points)); }
// Cannot be square if there aren't four points
if (points.Length != 4) { return false; }
// Takes two points, returns distance squared (to avoid sqrt and floating point precision errors)
Func<Point, Point, int> distSquared = (p1, p2) => (int)Math.Pow(p2.X - p1.X, 2) + (int)Math.Pow(p2.Y - p1.Y, 2);
// Calculate the squared distance of the first side
int firstDist = distSquared(points[3], points[0]);
// Compare the squared distances of the other three sides with the first side. Return false if not equal.
for (var i = 0; i < 3; i++) { if (distSquared(points[i], points[i + 1]) != firstDist) { return false; } }
// Compare the two diagonal distances. Return false if not equal.
if (distSquared(points[0], points[2]) != distSquared(points[1], points[3])) { return false; }
// Four sides and two diagonals are equal, return true
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment