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
using System ; using System . Collections . Generic ; class GFG { static int numberOfSquares ( int [ ] X , int [ ] Y , int N , int M ) { Dictionary < int , int > m1 = new Dictionary < int , int > ( ) ; Dictionary < int , int > m2 = new Dictionary < int , int > ( ) ; 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 ] ) ; if ( m1 . ContainsKey ( dist ) ) m1 [ dist ] ++ ; else m1 . Add ( dist , 1 ) ; } } for ( i = 0 ; i < M ; i ++ ) { for ( j = i + 1 ; j < M ; j ++ ) { int dist = Math . Abs ( Y [ i ] - Y [ j ] ) ; if ( m2 . ContainsKey ( dist ) ) m2 [ dist ] ++ ; else m2 . Add ( dist , 1 ) ; } } foreach ( KeyValuePair < int , int > entry in m1 ) { if ( m2 . ContainsKey ( entry . Key ) ) { ans += ( entry . Value * m2 [ entry . Key ] ) ; } } return ans ; } public static void Main ( ) { int [ ] X = { 1 , 3 , 7 } ; int [ ] Y = { 2 , 4 , 6 , 1 } ; int N = X . Length ; int M = Y . Length ; Console . WriteLine ( numberOfSquares ( X , Y , N , M ) ) ; } }