Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

int congestedCity() { double tmp = 0.0; int tmpIdx = 0; double total = 0.0; for(

ID: 3674793 • Letter: I

Question

int congestedCity() {

double tmp = 0.0;

int tmpIdx = 0;

double total = 0.0;

for(int i=0; i<n; i++) {

for(int j=0; j<5; j++) {

int x = getClosestCity(i); //this function gets the closest city

total += getDistance(j, x); //this function gets the distance between cities.

}

if (total < tmp ) {

tmp = total;

tmpIdx = i;

}

return tmpIdx;

}

The problem I am having is I need to get the distance of the 5 closest cities to EACH city on the list of california cities. And then find the city with the SMALLEST total 5 distances. Which will give the most congested city in California...

the function only gets the 5 distances for the first city on the list, it does not go through the entire list. What am I doing wrong?

Explanation / Answer

The mistake in the program is : you are returning the value (as return tmpIdx) in first iteration itself, so it won't go for the next, ie, second iteration. Please see the corrected code below :

int congestedCity() {

int tmpIdx = 0;
double total = 0.0;
for(int i=0; i<n; i++) {
double tmp = 0.0;
for(int j=0; j<5; j++) {
int x = getClosestCity(i); //this function gets the closest city
temp += getDistance(j, x); //this function gets the distance between cities.
}
if (tmp < total ) {
total = tmp;
tmpIdx = i;
}
}
return tmpIdx;
}