Created
November 23, 2018 17:39
-
-
Save miraris/0eadab13e9a3016e187a8491f6649013 to your computer and use it in GitHub Desktop.
order points in plane to form continuous lines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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