|
|
@@ -12,6 +12,7 @@ import java.io.InputStreamReader;
|
|
|
import java.net.HttpURLConnection;
|
|
|
import java.net.URL;
|
|
|
import java.util.ArrayList;
|
|
|
+import java.util.List;
|
|
|
|
|
|
@CrossOrigin
|
|
|
@RestController
|
|
|
@@ -51,12 +52,79 @@ public class MainController {
|
|
|
location.add(intersection.location.get(0));
|
|
|
coordinates.add(location);
|
|
|
}
|
|
|
-
|
|
|
}
|
|
|
System.out.println(coordinates);
|
|
|
return coordinates;
|
|
|
}
|
|
|
+ @GetMapping("/optimize-delivery-route")
|
|
|
+ @ResponseBody
|
|
|
+ public List<Coordinate> optimizeDeliveryRoute(List<Coordinate> coordinates) {
|
|
|
+
|
|
|
+ List<Integer> optimizedRoute = new ArrayList<>();
|
|
|
+ List<Coordinate> optimizedRouteCoordinates = new ArrayList<>();
|
|
|
+ boolean[] visited = new boolean[coordinates.size()];
|
|
|
+
|
|
|
+ int currentCoordinateIndex = 0;
|
|
|
+ optimizedRoute.add(currentCoordinateIndex);
|
|
|
+ visited[currentCoordinateIndex] = true;
|
|
|
+
|
|
|
+ while (optimizedRoute.size() < coordinates.size()) {
|
|
|
+ double minDistance = Double.MAX_VALUE;
|
|
|
+ int nearestCoordinateIndex = -1;
|
|
|
+
|
|
|
+ for (int i = 0; i < coordinates.size(); i++) {
|
|
|
+ if (!visited[i]) {
|
|
|
+ double distance = calculateDistance(coordinates.get(currentCoordinateIndex), coordinates.get(i));
|
|
|
+ if (distance < minDistance) {
|
|
|
+ minDistance = distance;
|
|
|
+ nearestCoordinateIndex = i;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ optimizedRoute.add(nearestCoordinateIndex);
|
|
|
+ visited[nearestCoordinateIndex] = true;
|
|
|
+ currentCoordinateIndex = nearestCoordinateIndex;
|
|
|
+ }
|
|
|
+ for (Integer integer : optimizedRoute) {
|
|
|
+ optimizedRouteCoordinates.add(coordinates.get(integer));
|
|
|
+ }
|
|
|
+ return optimizedRouteCoordinates;
|
|
|
+ }
|
|
|
+
|
|
|
+ private double calculateDistance(Coordinate c1, Coordinate c2) {
|
|
|
+ ArrayList<ArrayList<Double>> nodes;
|
|
|
+ try {
|
|
|
+ nodes = getNodesBetweenTwoCoordinates(c1.x, c1.y, c2.x, c2.y);
|
|
|
+ } catch (IOException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ return Double.MAX_VALUE;
|
|
|
+ }
|
|
|
+
|
|
|
+ double sumDistance = 0.0;
|
|
|
+
|
|
|
+ for (int i = 0; i < nodes.size() - 1; i++) {
|
|
|
+ ArrayList<Double> current = nodes.get(i);
|
|
|
+ ArrayList<Double> next = nodes.get(i + 1);
|
|
|
+ double dx = next.get(0) - current.get(0);
|
|
|
+ double dy = next.get(1) - current.get(1);
|
|
|
+ double distance = Math.sqrt(dx * dx + dy * dy);
|
|
|
+ sumDistance += distance;
|
|
|
+ }
|
|
|
|
|
|
+ return sumDistance;
|
|
|
+ }
|
|
|
|
|
|
+ class Coordinate {
|
|
|
+ double x;
|
|
|
+ double y;
|
|
|
+ public Coordinate(double x, double y) {
|
|
|
+ this.x = x;
|
|
|
+ this.y = y;
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+
|