import java.util.*;
public class TravellingSalesPerson
{
ArrayList<Integer> used = new ArrayList<Integer>();
public TravellingSalesPerson() {
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}};
int start = (int)(Math.random() * cities.length);
used.add(start);
System.out.println(cities[start]);
for (int c=0; c < cities.length; c++) {
start = path(cities, dist, start);
}
}
public int path(String[] cities, int[][] dist, int start) {
int totallargeez = -1;
int totallarge = 1000000;
for (int k=0; k < dist[start].length; k++) {
if (!(has(k, used))) {
if (totallarge > dist[start][k] && dist[start][k] != 0) {
totallarge = dist[start][k];
totallargeez = k;
}
}
}
if (totallargeez!= -1) {
System.out.println(cities[totallargeez]+" "+dist[start][totallargeez]);
used.add(totallargeez);
}
return totallargeez;
}
public boolean has (int search, ArrayList<Integer> searchArray) {
for (int h=0; h < searchArray.size(); h++) {
if (searchArray.get(h) == search) {
return true;
}
}
return false;
}
}
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.