forked from sat5297/hacktober-coding
-
Notifications
You must be signed in to change notification settings - Fork 1
/
NumberOfSquares.cpp
75 lines (58 loc) · 1.28 KB
/
NumberOfSquares.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count all the possible
// squares with given lines parallel
// to both the X and Y axis
int numberOfSquares(int X[], int Y[],
int N, int M)
{
// Stores the count of all possible
// distances in X[] & Y[] respectively
unordered_map<int, int> m1, m2;
int i, j, ans = 0;
// Find distance between all
// pairs in the array X[]
for (i = 0; i < N; i++) {
for (j = i + 1; j < N; j++) {
int dist = abs(X[i] - X[j]);
// Add the count to m1
m1[dist]++;
}
}
// Find distance between all
// pairs in the array Y[]
for (i = 0; i < M; i++) {
for (j = i + 1; j < M; j++) {
int dist = abs(Y[i] - Y[j]);
// Add the count to m2
m2[dist]++;
}
}
// Find sum of m1[i] * m2[i]
// for same distance
for (auto i = m1.begin();
i != m1.end(); i++) {
// Find current count in m2
if (m2.find(i->first)
!= m2.end()) {
// Add to the total count
ans += (i->second
* m2[i->first]);
}
}
// Return the final count
return ans;
}
// Driver Code
int main()
{
// Given lines
int X[] = { 1, 3, 7 };
int Y[] = { 2, 4, 6, 1 };
int N = sizeof(X) / sizeof(X[0]);
int M = sizeof(Y) / sizeof(Y[0]);
// Function Call
cout << numberOfSquares(X, Y, N, M);
return 0;
}