# How to Calculate a Valid Square in Java

## The challenge

Given the coordinates of four points in 2D space `p1``p2``p3` 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

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```class Solution {

public double dist(int[] p1, int[] p2) {
return (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[0] - p1[0]) * (p2[0] - p1[0]);
}

public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
int[][] p={p1,p2,p3,p4};
Arrays.sort(p, (l1, l2) -> l2[0] == l1[0] ? l1[1] - l2[1] : l1[0] - l2[0]);
return dist(p[0], p[1]) != 0 && dist(p[0], 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[0])   && dist(p[0],p[3])==dist(p[1],p[2]);
}

}
```Code language: Java (java)```

Tags:
Subscribe
Notify of