TSP

import java.util.*; public class TravelingSalesPerson { public TravelingSalesPerson() { String[] cities = {"Boston", "L.A.", "Las Vegas", "Atlanta", "Philadelphia", "Chicago", "Houston"}; int[][] dist = {{0, 2982, 2715, 1080, 310, 982, 1849}, {2982, 0, 270, 2174, 2710, 2015, 1549}, {2715, 270, 0, 1959, 2473, 1747, 1473}, {1080, 2174, 1959, 0, 777, 715, 794 }, {310, 2710, 2473, 777, 0, 785, 1548}, {982, 2015, 1747, 715, 785, 0, 1084}, {1849, 1549, 1473, 794, 1548, 1084, 0}}; /* * The nearest neighbour algorithm was one of the first algorithms * used to determine a solution to the travelling salesman problem. * In it, the salesman starts at a random city and repeatedly visits * the nearest city until all have been visited. It quickly yields a * short tour, but usually not the optimal one. * */ int start = 4;//this is philly, but you want to make this random //print the city that is the starting point - one that coorelates to start variable System.out.println(Arrays.toString(nearNeighbor(cities, dist, start))); //print the route that you find in your nearest neighbor function //also print the miles between each city } public String[] nearNeighbor(String[] cities, int[][] dist, int start){ String [] nnCities = new String[7]; int min = 1000000; int spot = 0; int og = start; for(int i = 0; i < dist.length; i++){ nnCities[i] = cities[start]; for (int b = 0; b < dist.length; b++){ if (min > dist[start][b] && dist[start][b] !=0){ min = dist[start][b]; spot = b; } if (b == dist.length - 1){ for (int c = 0; c < dist.length; c++){ for (int d = 0; d < dist.length; d++){ if (d == og){ dist[c][d] = 0; } if (d == spot){ dist[c][d] = 0; } } } } } min = 1000000; start = spot; } return nnCities; } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.