javascript - How to properly use a loop to find shortest route between multiple coordinates?
问题描述
I have an array of objects each containing an x,y coordinate. I would like to calculate the shortest path between the objects in JavaScript.
The array of islands will also always be random so the route needs to be calculated dynamically.
I was unable to properly implement Dijkstra's algorithm in JavaScript. I have tried to use several path-finding algorithms from other languages and was unsuccessful.
Objects in array
var selected_islands= [{
id: 0,
name: "Island1",
x: 212,
y: 1271,
size: 50,
}, {
id: 1,
name: "Island2",
x: 495,
y: 226,
size: 15,
}, {
id: 2,
name: "Island3",
x: 473,
y: 832,
size: 25,
}]
Run method on all Islands in array
for (i in selected_islands) {
duped = selected_islands[i].findClosestIsland(duped);
console.log(duped);
}
Inside my Island Class
compareDistance(island) {
return this.pythagoreanTheorem(island.x, island.y);
}
findClosestIsland(duped) {
var lowest_val = Number.MAX_SAFE_INTEGER; // Setting high initial value
for (i in duped) {
if (this.compareDistance(selected_islands[i]) < lowest_val && this.compareDistance(selected_islands[i]) != 0) {
lowest_val = this.compareDistance(selected_islands[i]);
closest_island = selected_islands[i];
}
}
duped.splice(0,1); // Immutable, ruins array
return duped;
}
splice method ruins my duplicate array. The logic is a bit fuzzy to me. Should I create a new array of "visited_islands" and loop through that every time?
Thanks for any insight :)
解决方案
推荐阅读
- javascript - 引导问题中的单选按钮 onclick
- angular - 如何从搜索栏输入将数据从 html 文件传递到 Ionic(最新)中的 .ts 文件
- html - 影响标题文本的 Css 背景覆盖
- python - python -c cmd 将等待所有进程完成
- android - IllegalStateException:链接没有设置 NavController
- android - 无法从圆角矩形按钮中删除背景
- javascript - Jquery 像 Angular5 中的 DOM 选择
- c# - 使用 where 子句从数据表中获取值到数据表中
- excel - 无法在 MS-Excel Office365 的脚本实验室中创建片段和查看示例
- rabbitmq - 绑定密钥或路由密钥