Count squares possible from M and N straight lines parallel to X and Y axis respectively | 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 ; Given lines ; Function Call
function numberOfSquares ( X , Y , N , M ) { var m1 = new Map ( ) , m2 = new Map ( ) ; var i , j , ans = 0 ; for ( i = 0 ; i < N ; i ++ ) { for ( j = i + 1 ; j < N ; j ++ ) { var dist = Math . abs ( X [ i ] - X [ j ] ) ; if ( m1 . has ( dist ) ) m1 . set ( dist , m1 . get ( dist ) + 1 ) else m1 . set ( dist , 1 ) ; } } for ( i = 0 ; i < M ; i ++ ) { for ( j = i + 1 ; j < M ; j ++ ) { var dist = Math . abs ( Y [ i ] - Y [ j ] ) ; if ( m2 . has ( dist ) ) m2 . set ( dist , m2 . get ( dist ) + 1 ) else m2 . set ( dist , 1 ) ; } } m1 . forEach ( ( value , key ) => { if ( m2 . has ( key ) ) { ans += ( value * m2 . get ( key ) ) ; } } ) ; return ans ; } var X = [ 1 , 3 , 7 ] ; var Y = [ 2 , 4 , 6 , 1 ] ; var N = X . length ; var M = Y . length ; document . write ( numberOfSquares ( X , Y , N , M ) ) ;