// Java implementation of the above approach
import java.util.*;
public class GFG
{
// Function to return the number of non coincident
// pairs of points with manhattan distance
// equal to euclidean distance
static int findManhattanEuclidPair(int[][] arr, int n)
{
// To store frequency of all distinct Xi
Map<Integer, Integer> X = new HashMap<Integer, Integer>();
// To store Frequency of all distinct Yi
Map<Integer, Integer> Y = new HashMap<Integer, Integer>();
// To store Frequency of all distinct
// points (Xi, Yi);
Map<List<Integer>, Integer> XY = new HashMap<List<Integer>, Integer>();
for (int i = 0; i < n; i++) {
int xi = arr[i][0];
int yi = arr[i][1];
// Hash xi coordinate
if (!X.containsKey(xi))
X.put(xi, 0);
X.put(xi, X.get(xi) + 1);
// Hash yi coordinate
if (!Y.containsKey(yi))
Y.put(yi, 0);
Y.put(yi, Y.get(yi) + 1);
// Hash the point (xi, yi)
if (!XY.containsKey(Arrays.asList(xi, yi)))
XY.put(Arrays.asList(xi, yi), 0);
XY.put( Arrays.asList(xi, yi), XY.get(Arrays.asList(xi, yi)) + 1);
}
int xAns = 0, yAns = 0, xyAns = 0;
// find pairs with same Xi
for (Map.Entry<Integer, Integer> xCoordinatePair : X.entrySet())
{
int xFrequency = xCoordinatePair.getValue();
// calculate ((xFrequency) C2)
int sameXPairs
= (xFrequency * (xFrequency - 1)) / 2;
xAns += sameXPairs;
}
// find pairs with same Yi
for (Map.Entry<Integer, Integer> yCoordinatePair : Y.entrySet()) {
int yFrequency = yCoordinatePair.getValue();
// calculate ((yFrequency) C2)
int sameYPairs
= (yFrequency * (yFrequency - 1)) / 2;
yAns += sameYPairs;
}
// find pairs with same (Xi, Yi)
for (Map.Entry<List<Integer>, Integer> XYPair : XY.entrySet())
{
int xyFrequency = XYPair.getValue();
// calculate ((xyFrequency) C2)
int samePointPairs
= (xyFrequency * (xyFrequency - 1)) / 2;
xyAns += samePointPairs;
}
return (xAns + yAns - (2 * xyAns));
/* we are subtracting 2 * xyAns because we have counted
let say A,B coinciding points two times in xAns and
yAns which should not be add to the final answer so
we are subtracting xyAns 2 times. */
}
// Driver Code
public static void main(String[] args)
{
int[][] arr
= { { 1, 2 }, { 1, 2 }, { 4, 3 }, { 1, 3 } };
int n = arr.length;
System.out.println(findManhattanEuclidPair(arr, n));
}
}
// This code is contributed by phasing17