Skip to content

How to Calculate a Valid Square in Java

The challenge

Given the coordinates of four points in 2D space p1p2p3 and p4, return true if the four points construct a square.

The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order.

valid square has four equal sides with positive length and four equal angles (90-degree angles).

Example 1:

Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: true

Example 2:

Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]
Output: false

Example 3:

Input: p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]
Output: true

Constraints:

  • p1.length == p2.length == p3.length == p4.length == 2
  • -104 <= xi, yi <= 104

The solution in Java code

class Solution { public double dist(int[] p1, int[] p2) { return (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[] - p1[]) * (p2[] - p1[]); } public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) { int[][] p={p1,p2,p3,p4}; Arrays.sort(p, (l1, l2) -> l2[] == l1[] ? l1[1] - l2[1] : l1[] - l2[]); return dist(p[], p[1]) != && dist(p[], p[1]) == dist(p[1], p[3]) && dist(p[1], p[3]) == dist(p[3], p[2]) && dist(p[3], p[2]) == dist(p[2], p[]) && dist(p[],p[3])==dist(p[1],p[2]); } }
Code language: Java (java)

See also  How to Purge the BinLog for MySQL and MariaDB
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x