Skip to content

Instantly share code, notes, and snippets.

@subzey
Created May 10, 2018 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save subzey/0cf32af458a037608a6d6264d9353815 to your computer and use it in GitHub Desktop.
Save subzey/0cf32af458a037608a6d6264d9353815 to your computer and use it in GitHub Desktop.
function distanceBetweenPoints(p1, p2) {
return Math.hypot(p1.x - p2.x, p1.y - p2.y);
}
function closestPoints(points) {
let closestPoints = [];
let smallestDistance = Infinity;
for (let i = 1; i < points.length; i++) {
for (let j = 0; j < i; j++) {
const distance = distanceBetweenPoints(points[i], points[j]);
if (distance < smallestDistance) {
smallestDistance = distance;
closestPoints[0] = points[i];
closestPoints[1] = points[j];
}
}
}
return closestPoints;
}
const points = [];
const POINTS_COUNT = 1000;
const FLIPPED_POINTS_COUNT = 500;
for (let v = 0; v < POINTS_COUNT; v++) {
const x = Math.random();
const y = Math.random();
if (v < FLIPPED_POINTS_COUNT) {
points.push({ x, y });
} else {
points.push({ y, x });
}
}
console.time('closestPoints()');
closestPoints(points);
console.timeEnd('closestPoints()');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment