Advertisement
Guest User

tsp object

a guest
Aug 16th, 2018
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. package travelling_salesman_package;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4.  
  5. import given_functions.CS2004;
  6.  
  7. public class TSPObject {
  8.  
  9. private ArrayList<Integer> tour;
  10. private double fitness;
  11.  
  12. public TSPObject(ArrayList<Integer> t, int noOfCities) {
  13. if(t == null) {
  14. tour = RandomPerm(noOfCities);
  15. } else {
  16. tour = (ArrayList<Integer>) t.clone();
  17. }
  18. }
  19. //Random starting point for the Tour
  20. //Random Permutation
  21. public TSPObject(int n) {
  22. tour = RandomPerm(n);
  23. }
  24.  
  25. //n = number of cities
  26.  
  27. private ArrayList<Integer> RandomPerm(int n) {
  28.  
  29. tour = new ArrayList<>();
  30.  
  31. //need to take away 1 since index starts at 0
  32. for (int i = 0; i <n - 1;i++ )
  33. {
  34. tour.add(i);
  35. }
  36. Collections.shuffle(tour); //Shuffles the cities to create a random permutation of a list
  37. return tour;
  38.  
  39.  
  40. }
  41.  
  42.  
  43.  
  44. public double fitnessFunction(double[][] distances) {
  45. double s = 0;
  46. for (int i = 0; i < tour.size()-1; i++)
  47. {
  48.  
  49. int a = tour.get(i);
  50. int b = tour.get(i+1);
  51. s = s + distances[a][b]; //This calculates the distance
  52. }
  53. Integer end_city = tour.get(tour.size()-1);
  54. Integer start_city = tour.get(0);
  55. s = s + distances[end_city][start_city]; //uses the distances to create a tour
  56.  
  57. fitness = s;
  58. return s;
  59. }
  60.  
  61.  
  62.  
  63. //creates small change
  64. public void smallChange() {
  65. ArrayList<Integer> tour2 = new ArrayList<Integer>();
  66. tour2 = (ArrayList<Integer>)tour.clone();
  67. int b = CS2004.UI(0,tour2.size()-1);
  68. int c = CS2004.UI(0,tour2.size()-1);
  69.  
  70. Collections.swap(tour, b, c);
  71. }
  72.  
  73.  
  74.  
  75. public ArrayList<Integer> getTour() {
  76. return tour;
  77. }
  78.  
  79. public double getFitness() {
  80. return fitness;
  81. }
  82.  
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement