Count squares possible from M and N straight lines parallel to X and Y axis respectively | Java 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
import java . io . * ; import java . util . * ; class GFG { static int numberOfSquares ( int [ ] X , int [ ] Y , int N , int M ) { HashMap < Integer , Integer > m1 = new HashMap < Integer , Integer > ( ) ; HashMap < Integer , Integer > m2 = new HashMap < Integer , Integer > ( ) ; int i , j , ans = 0 ; for ( i = 0 ; i < N ; i ++ ) { for ( j = i + 1 ; j < N ; j ++ ) { int dist = Math . abs ( X [ i ] - X [ j ] ) ; m1 . put ( dist , m1 . getOrDefault ( dist , 0 ) + 1 ) ; } } for ( i = 0 ; i < M ; i ++ ) { for ( j = i + 1 ; j < M ; j ++ ) { int dist = Math . abs ( Y [ i ] - Y [ j ] ) ; m2 . put ( dist , m2 . getOrDefault ( dist , 0 ) + 1 ) ; } } for ( Map . Entry < Integer , Integer > entry : m1 . entrySet ( ) ) { if ( m2 . containsKey ( entry . getKey ( ) ) ) { ans += ( entry . getValue ( ) * m2 . get ( entry . getKey ( ) ) ) ; } } return ans ; } public static void main ( String [ ] args ) { int X [ ] = { 1 , 3 , 7 } ; int Y [ ] = { 2 , 4 , 6 , 1 } ; int N = X . length ; int M = Y . length ; System . out . println ( numberOfSquares ( X , Y , N , M ) ) ; } }