Skip to content

Commit d13e753

Browse files
Create Check Square.cpp
1 parent 28f46ca commit d13e753

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
Check Square
3+
Send Feedback
4+
You are given four points on a two-dimensional coordinate system.
5+
Can you check if those four points make a square?
6+
Example:
7+
Let the input be [1,0,2,1] and [0,1,1,2].
8+
So, the coordinates of the four points be [ {1, 0}, {0, 1}, {2, 1}, {1, 2} ]
9+
example
10+
11+
From the above image, we can see that it is a square. Thus, the output will be ‘Yes’.
12+
Input format:
13+
The first line of input contains an integer ‘T’ denoting the number of test cases.
14+
15+
The first line of each test case contains four space-separated integers representing x-coordinates of the four points.
16+
17+
The second line of each test case contains four space-separated integers representing y-coordinates of the four points.
18+
Output format :
19+
For each test case, print ‘Yes’ if four points make a square otherwise print ‘No’.
20+
Note:
21+
Don’t print anything, just return True if four points make a square otherwise return False.
22+
Constraints:
23+
1 <= T <= 10^4
24+
-10^9 <= xi, yi <= 10^9
25+
26+
Time limit: 1 sec
27+
Sample Input 1:
28+
2
29+
1 0 2 1
30+
0 1 1 2
31+
1 0 0 1
32+
1 0 1 2
33+
Sample Output 1:
34+
Yes
35+
No
36+
Explanation For Sample Input 1:
37+
Test Case 1: Refer to the example described above.
38+
39+
Test Case 2:
40+
The quadrilateral for the given four points is represented below.
41+
test case 2
42+
43+
As we can clearly see this is not a square. Thus, the answer will be ‘No’.
44+
Sample Input 2:
45+
2
46+
1 2 4 2
47+
0 2 4 2
48+
0 1 2 3
49+
1 -1 2 0
50+
Sample Output 2:
51+
No
52+
Yes
53+
*/
54+
55+
56+
57+
/*
58+
Time Complexity: O(1)
59+
Space Complexity: O(1)
60+
*/
61+
62+
#include <algorithm>
63+
64+
bool isSquare(vector<int> x, vector<int> y) {
65+
vector<long long> distSq;
66+
for(int i = 0; i < 4; i++) {
67+
for(int j = i + 1 ; j < 4; j++) {
68+
long long dist = (1LL * (x[i] - x[j]) * (x[i] - x[j])) + (1LL * (y[i] - y[j]) * (y[i] - y[j]));
69+
distSq.push_back(dist);
70+
}
71+
}
72+
73+
sort(distSq.begin(), distSq.end());
74+
75+
76+
//Check if the distance of all the sides are equal
77+
//and the length of the diagonals are equal to the length of each side * root(2).
78+
if(distSq[0] == distSq[1] &&
79+
distSq[1] == distSq[2] &&
80+
distSq[2] == distSq[3] &&
81+
distSq[4] == distSq[5] &&
82+
distSq[0] * 2LL == distSq[4] &&
83+
distSq[0] > 0){
84+
return true;
85+
}
86+
return false;
87+
}

0 commit comments

Comments
 (0)