Skip to content

Instantly share code, notes, and snippets.

@miraris
Created November 23, 2018 17:39
Show Gist options
  • Save miraris/0eadab13e9a3016e187a8491f6649013 to your computer and use it in GitHub Desktop.
Save miraris/0eadab13e9a3016e187a8491f6649013 to your computer and use it in GitHub Desktop.
order points in plane to form continuous lines
const distance = (p1, p2) => (p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2;
const findNearestIndex = (point, list) => {
let nearestDistSquared = Infinity;
let nearestIndex;
for (let i = 0; i < list.length; i++) {
const curPoint = list[i];
const distsq = distance(point, curPoint);
if (distsq < nearestDistSquared) {
nearestDistSquared = distsq;
nearestIndex = i;
}
}
return nearestIndex;
};
const order = (arr) => {
const orderedList = [arr.shift()];
while (arr.length > 0) {
const nearestIndex = findNearestIndex(orderedList[orderedList.length - 1], arr);
orderedList.push(arr.splice(nearestIndex, 1)[0]);
}
return orderedList;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment