Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k)
such that the distance between i
and j
equals the distance between i
and k
(the order of the tuple matters).
Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).
Example:
Input: [[0,0],[1,0],[2,0]]
Output: 2
Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
/**
* Iterate through ES6 Map is way more faster than iterate through Object
* Ref: https://jsperf.com/es6-map-vs-object-properties/2
* @param {number[][]} points
* @return {number}
*/
var numberOfBoomerangs = function(points) {
"use strict";
function calDist(pointA, pointB) {
return Math.pow(pointA[0]-pointB[0], 2) + Math.pow(pointA[1]-pointB[1], 2);
}
let result = 0;
for (let i = 0; i < points.length; i++) {
let map = new Map();
for (let j = 0; j < points.length; j++) {
if (i === j) {
continue;
}
let dist = calDist(points[i], points[j]);
if (map.get(dist) === undefined) {
map.set(dist, 0);
}
map.set(dist, map.get(dist)+1);
}
map.forEach((item) => result += item * (item-1));
}
return result;
};