Advertisement
Guest User

Untitled

a guest
May 24th, 2017
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.94 KB | None | 0 0
  1. package APS2;
  2.  
  3.  
  4. import java.util.ArrayList;
  5. import java.util.Random;
  6.  
  7. public class TravellingSalesman {
  8.    
  9.     ArrayList nodes;
  10.    
  11.     public TravellingSalesman() {
  12.         nodes = new ArrayList();
  13.     }
  14.    
  15.     static class Node {
  16.         int x;
  17.         int y;
  18.         public Node(int x, int y) {
  19.             this.x = x;
  20.             this.y = y;
  21.         }
  22.     }
  23.     /**
  24.      * To solve the traveling salesman problem (TSP) you need to find a shortest
  25.      * tour over all nodes in the graph where each node must be visited exactly
  26.      * once. You need to finish at the origin node.
  27.      *
  28.      * In this task we will consider complete undirected graphs only with
  29.      * Euclidean distances between the nodes.
  30.      */
  31.  
  32.     /**
  33.      * Adds a node to a graph with coordinates x and y. Assume the nodes are
  34.      * named by the order of insertion.
  35.      *
  36.      * @param x X-coordinate
  37.      * @param y Y-coordinate
  38.      */
  39.     public void addNode(int x, int y){
  40.         nodes.add(new Node(x, y));
  41.     }
  42.  
  43.     /**
  44.      * Returns the distance between nodes v1 and v2.
  45.      *
  46.      * @param v1 Identifier of the first node
  47.      * @param v2 Identifier of the second node
  48.      * @return Euclidean distance between the nodes
  49.      */
  50.     public double getDistance(int v1, int v2) {
  51.         Node n1 = (Node) nodes.get(v1);
  52.         Node n2 = (Node) nodes.get(v2);
  53.        
  54.         return Math.sqrt(Math.pow(n2.x - n1.x, 2) + Math.pow(n2.y - n1.y, 2));
  55.     }        
  56.     int[] best;
  57.     double minimum = Integer.MAX_VALUE;
  58.    
  59.     public void permute(int[] arr, int index, int start) {
  60.        
  61.         if (index >= arr.length - 1) {
  62.             double current = 0;
  63.             current += getDistance(start, arr[0]);
  64.             for (int i = 0; i < arr.length-1; i++) {
  65.                 current += getDistance(arr[i], arr[i+1]);
  66.                 if (current > minimum) {
  67.                     break;
  68.                 }
  69.  
  70.             }
  71.             current += getDistance(arr[arr.length-1], start);
  72.             if (current < minimum) {
  73.                 minimum = current;
  74.                 for (int i = 0; i < arr.length; i++) {
  75.                     this.best[i] = arr[i];
  76.                 }
  77.             }  
  78.         }
  79.         for (int i = index; i < arr.length; i++) {
  80.             int t = arr[index];
  81.             arr[index] = arr[i];
  82.             arr[i] = t;
  83.  
  84.             permute(arr, index+1, start);
  85.  
  86.             t = arr[index];
  87.             arr[index] = arr[i];
  88.             arr[i] = t;
  89.         }
  90.     }
  91.    
  92.    
  93.     /**
  94.      * Finds and returns an optimal shortest tour from the origin node and
  95.      * returns the order of nodes to visit.
  96.      *
  97.      * Implementation note: Avoid exploring paths which are obviously longer
  98.      * than the existing shortest tour.
  99.      *
  100.      * @param start Index of the origin node
  101.      * @return List of nodes to visit in specific order
  102.      */
  103.     public int[] calculateExactShortestTour(int start){
  104.  
  105.         int[] arrayToPermute = new int[nodes.size()-1];
  106.  
  107.         for (int i = 0; i < nodes.size()-1; i++) {
  108.             if (i < start) {
  109.                 arrayToPermute[i] = i;
  110.             } else {
  111.                 arrayToPermute[i] = i+1;
  112.             }
  113.         }
  114.         best = new int[arrayToPermute.length];
  115.         permute(arrayToPermute, 0, start);
  116.  
  117.         int[] shortestTourArray = new int[best.length+2];
  118.         shortestTourArray[0] = start;
  119.         shortestTourArray[shortestTourArray.length-1] = start;
  120.        
  121.         for (int i = 1; i <= best.length; i++) {
  122.             shortestTourArray[i] = best[i-1];
  123.         }
  124.    
  125.         return shortestTourArray;
  126.     }
  127.  
  128.     /**
  129.      * Returns an optimal shortest tour and returns its distance given the
  130.      * origin node.
  131.      *
  132.      * @param start Index of the origin node
  133.      * @return Distance of the optimal shortest TSP tour
  134.      */
  135.     public double calculateExactShortestTourDistance(int start){
  136.         double total = 0;
  137.         int[] tempNodes = calculateExactShortestTour(start);
  138.         for (int i = 0; i < tempNodes.length-1; i++) {
  139.             total += getDistance(tempNodes[i], tempNodes[i+1]);
  140.         }
  141.         return total;
  142.     }  
  143.  
  144.     /**
  145.      * Returns an approximate shortest tour and returns the order of nodes to
  146.      * visit given the origin node.
  147.      *
  148.      * Implementation note: Use a greedy nearest neighbor approach to construct
  149.      * an initial tour. Then use iterative 2-opt method to improve the
  150.      * solution.
  151.      *
  152.      * @param start Index of the origin node
  153.      * @return List of nodes to visit in specific order
  154.      */
  155.     public int[] calculateApproximateShortestTour(int start){
  156.         throw new UnsupportedOperationException("You need to implement this function!");
  157.     }
  158.  
  159.     /**
  160.      * Returns an approximate shortest tour and returns its distance given the
  161.      * origin node.
  162.      *
  163.      * @param start Index of the origin node
  164.      * @return Distance of the approximate shortest TSP tour
  165.      */
  166.     public double calculateApproximateShortestTourDistance(int start){
  167.         double total = 0;
  168.         int tour[] = calculateApproximateShortestTour(start);
  169.         for (int i = 0; i < tour.length-1; i++) {
  170.             total += getDistance(tour[i], tour[i+1]);
  171.         }
  172.         return total;
  173.     }
  174.  
  175.     /**
  176.      * Constructs a Hamiltonian cycle by starting at the origin node and each
  177.      * time adding the closest neighbor to the path.
  178.      *
  179.      * Implementation note: If multiple neighbors share the same distance,
  180.      * select the one with the smallest id.
  181.      *
  182.      * @param start Origin node
  183.      * @return List of nodes to visit in specific order
  184.      */
  185.     public int[] nearestNeighborGreedy(int start){
  186.         throw new UnsupportedOperationException("You need to implement this function!");
  187.     }
  188.  
  189.     /**
  190.      * Improves the given route using 2-opt exchange.
  191.      *
  192.      * Implementation note: Repeat the procedure until the route is not
  193.      * improved in the next iteration anymore.
  194.      *
  195.      * @param route Original route
  196.      * @return Improved route using 2-opt exchange
  197.      */
  198.     private int[] twoOptExchange(int[] route) {
  199.         throw new UnsupportedOperationException("You need to implement this function!");
  200.     }
  201.  
  202.     /**
  203.      * Swaps the nodes i and k of the tour and adjusts the tour accordingly.
  204.      *
  205.      * Implementation note: Consider the new order of some nodes due to the
  206.      * swap!
  207.      *
  208.      * @param route Original tour
  209.      * @param i Name of the first node
  210.      * @param k Name of the second node
  211.      * @return The newly adjusted tour
  212.      */
  213.     public int[] twoOptSwap(int[] route, int i, int k) {
  214.         throw new UnsupportedOperationException("You need to implement this function!");
  215.     }
  216.  
  217.     /**
  218.      * Returns the total distance of the given tour i.e. the sum of distances
  219.      * of the given path add the distance between the final and initial node.
  220.      *
  221.      * @param tour List of nodes in the given order
  222.      * @return Traveled distance of the tour
  223.      */
  224.     public double calculateDistanceTravelled(int[] tour){
  225.         double total = 0;
  226.         for (int i = 0; i < tour.length-1; i++) {
  227.             total += getDistance(tour[i], tour[i+1]);
  228.         }
  229.         return total + getDistance(tour[tour.length-1], tour[0]);
  230.     }
  231.  
  232.     public static void main(String[] args) {
  233.         TravellingSalesman ts = new TravellingSalesman();
  234.  
  235.         Random r = new Random(35164);
  236.  
  237.         for (int i = 0; i < 12; i++) {
  238.             ts.addNode(r.nextInt(50), r.nextInt(50));
  239.         }
  240.        
  241.         System.out.println(ts.calculateDistanceTravelled(ts.calculateExactShortestTour(0)));
  242.         System.out.println(ts.calculateExactShortestTourDistance(0));
  243.        
  244.         ts.addNode(r.nextInt(50), r.nextInt(50));
  245.         System.out.println(ts.calculateDistanceTravelled(ts.calculateExactShortestTour(0)));
  246.         System.out.println(ts.calculateExactShortestTourDistance(0));
  247.  
  248.     }
  249. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement