Question is from here:
Consider a list of four points on a plane; the points have integral coordinates, and their order is irrelevant. The four points determine a square if the distances between them are all equal, and the lengths of the two diagonals are also equal. For instance, the following lists are all squares:
(0,0), (0,1), (1,1), (1,0) — the unit square
(0,0), (2,1), (3,-1), (1, -2) — square not aligned to axis
(0,0), (1,1), (0,1), (1,0) — unit square, in different order
And the following lists do not represent squares:
(0,0), (0,2), (3,2), (3,0) — rectangle
(0,0), (3,4), (8,4), (5,0) — rhombus
(0,0), (0,0), (1,1), (0,0) — degenerate
(0,0), (0,0), (1,0), (0,1) — degenerate
The degenerate square that consists of four repetitions of a single point may be considered either square, or not.
Your task is to write a function that determines if four input points determine a square.
Solution:
public class Four_Points_Determine_A_Square {
public static void main(String[] args) {
System.out.println(isSquare(new Pair(0, 0), new Pair(0, 1),
new Pair(1, 1), new Pair(1, 0)));
System.out.println(isSquare(new Pair(0, 0), new Pair(2, 1),
new Pair(3, -1), new Pair(1, -2)));
System.out.println(isSquare(new Pair(0, 0), new Pair(1, 1),
new Pair(0, 1), new Pair(1, 0)));
System.out.println(isSquare(new Pair(0, 0), new Pair(0, 2),
new Pair(3, 2), new Pair(3, 0)));
System.out.println(isSquare(new Pair(0, 0), new Pair(3, 4),
new Pair(8, 4), new Pair(5, 0)));
}
private static boolean isSquare(Pair p1, Pair p2, Pair p3, Pair p4){
double dis1, dis2, dis3;
//calculating distance - reference is p1
dis1 = Math.pow((p1.returnX() - p2.returnX()), 2) +
Math.pow((p1.returnY() - p2.returnY()), 2);
dis2 = Math.pow((p1.returnX() - p3.returnX()), 2) +
Math.pow((p1.returnY() - p3.returnY()), 2);
dis3 = Math.pow((p1.returnX() - p4.returnX()), 2) +
Math.pow((p1.returnY() - p4.returnY()), 2);
//two smaller distances are side and
//largest is the diagonal
double[] points = {dis1, dis2, dis3};
java.util.Arrays.sort(points);
//two smaller distances are side
//and must be equal
if(points[0] != points[1])
return false;
//Pythagorean theorem: sum of square of sides
//is equal to square of diagonal
if(points[0] + points[1] != points[2])
return false;
return true;
}
//inner class
static class Pair{
private int x;
private int y;
public Pair(int x, int y){
this.x = x;
this.y = y;
}
public void setX(int x){
this.x = x;
}
public int returnX(){
return x;
}
public void setY(int y){
this.y = y;
}
public int returnY(){
return y;
}
}
}
Output:
true true true false false