function:RenderSidePart pageleftbodycaption pageleftbody sidenote Main.DistanceChart-SideNote Main.SideNote Site.SideNote

# Distance Chart

Page 183 from the text has the starter code for DistanceChart.

# Exercises

1. make Constructors for the DistanceChart class
2. Implement findNearestCity
3. Make a tester class and use the information from the example on page 182.
4. complete part(a) and part (b)

If you don't have enough time to make your own tester, here is one I made:

import java.util.*;

public class DistanceChartTester
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<String>();

int[][] dist = new int[names.size()][names.size()];
for (int i=0; i< names.size(); i++)
{
dist[i][i]=0;
}
dist[0][1]=936;
dist[0][2]=550;
dist[1][2]=554;
dist[0][3]=719;
dist[1][3]=1547;
dist[2][3]=1018;
dist[0][4]=540;
dist[1][4]=396;
dist[2][4]=309;
dist[3][4]=1181;
for(int i=0; i<names.size(); i++)
for(int j=0; j< names.size(); j++)
dist[j][i]=dist[i][j];

//Print the distance table
System.out.println("\nDistance Table is:");

for(int i=0; i<names.size(); i++){
System.out.format("%-12s",names.get(i));
for(int j=0; j< names.size(); j++){
System.out.format("%6d",dist[i][j]);
}
System.out.println();
}
DistanceChart dc =  new DistanceChart(names, dist);
List<String> itinerary = dc.makeItinerary();

System.out.println("\nComputed Itinerary is:");
for(int i=0; i< itinerary.size(); i++){
System.out.format("%2d. %-12s\n",i+1,itinerary.get(i));
}
System.out.println("\nExpected\n 1. Dallas\n 2. Atlanta\n 3. Washington\n 4. Cleveland\n 5. Boston");
}
}



If you just have time only for part (a) and part (b), here is one way you can implement the findNearestCity method:

public int findNearestCity(int i, boolean[] visited)
{
//not shown
//find index of first city not visited:
int start=0;
while (start < visited.length && visited[start])
start++;

int min=distances[i][start];
int minIndex=start;
for(int j=start+1; j< visited.length; j++)
{
if (!visited[j] && distances[i][j] < min){
min=distances[i][j];
minIndex=j;
}
}
return minIndex;
}