Count squares possible from M and N straight lines parallel to X and Y axis respectively | C ++ program for the above approach ; Function to count all the possible squares with given lines parallel to both the X and Y axis ; Stores the count of all possible distances in X [ ] & Y [ ] respectively ; Find distance between all pairs in the array X [ ] ; Add the count to m1 ; Find distance between all pairs in the array Y [ ] ; Add the count to m2 ; Find sum of m1 [ i ] * m2 [ i ] for same distance ; Find current count in m2 ; Add to the total count ; Return the final count ; Driver Code ; Given lines ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfSquares ( int X [ ] , int Y [ ] , int N , int M ) { unordered_map < int , int > m1 , m2 ; int i , j , ans = 0 ; for ( i = 0 ; i < N ; i ++ ) { for ( j = i + 1 ; j < N ; j ++ ) { int dist = abs ( X [ i ] - X [ j ] ) ; m1 [ dist ] ++ ; } } for ( i = 0 ; i < M ; i ++ ) { for ( j = i + 1 ; j < M ; j ++ ) { int dist = abs ( Y [ i ] - Y [ j ] ) ; m2 [ dist ] ++ ; } } for ( auto i = m1 . begin ( ) ; i != m1 . end ( ) ; i ++ ) { if ( m2 . find ( i -> first ) != m2 . end ( ) ) { ans += ( i -> second * m2 [ i -> first ] ) ; } } return ans ; } int main ( ) { 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 ] ) ; cout << numberOfSquares ( X , Y , N , M ) ; return 0 ; }