[LC 447] Boomerangs

Note that the problem only requires to return the number of boomerangs.
For every i, we capture the number of points equidistant from i. Now for this i, we have to calculate all possible permutations of (j,k) from these equidistant points.
    public int numberOfBoomerangs(int[][] points) {
        Map<Integer, Integer> map = new HashMap(); // stores distance to number ( of equidistant points) map
        int res = 0;
        for (int i = 0; i < points.length; i++) {
            for (int j = 0; j < points.length; j++) {
                if (i == j) continue;
                int d = distance(points[i], points[j]); // distance calculation ignores square roots
                map.put(d, map.getOrDefault(d, 0)+1);
            }
            for (int key : map.keySet()){
                int val = map.get(key);
                res += val * (val-1); // all combinations: first point has n choices, second has n-1 choices (n = val)
            }
            map.clear();
        }
        return res;
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s