首页 > 解决方案 > 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?

Canvas Output

Thanks for any insight :)

标签: javascriptarraysobjectnested-loopspath-finding

解决方案


推荐阅读