Reputation: 57
I have this code:
int sum = 0;
for(int i = 0; i < POPULATION_SIZE; i++){ // loop through the population (0-99)
for(int j = 0; j < 16; j++){ // loop through the individuals (in this case the cities)
sum = COST[j][j+1];
}
fitness[i] = sum;
}
I am trying to add all the COSTS. Sum is meant to equal the the total of adding all the elements.
The problem I'm facing is that each time the loop runs, sum is set to the next value, as aposed to the total of adding the previous and the current values.
Given people's answers I can now see my rather foolish error. Is this a case of remembered fundamentals before you over complicate?
Upvotes: 0
Views: 57
Reputation: 700262
You are assigning each value to the variable, you need to add the value to it. You can use the +=
operator for that.
To get a sum for each population you need to initialise the variable inside the outer loop:
for(int i = 0; i < POPULATION_SIZE; i++){ // loop through the population (0-99)
int sum = 0;
for(int j = 0; j < 16; j++){ // loop through the individuals (in this case the cities)
sum += COST[j][j+1];
}
fitness[i] = sum;
}
Note: I don't know how your data is arranged, but in COST[j][j+1]
you are using the variable j
for both indexes, it seems like you should use i
for one of them.
Upvotes: 1
Reputation: 1956
you add += this operator to sum the values;
int sum = 0;
for(int i = 0; i < POPULATION_SIZE; i++){ // loop through the population (0-99)
for(int j = 0; j < 16; j++){ // loop through the individuals (in this case the cities)
sum += COST[j][j+1];
}
fitness[i] = sum;
}
Upvotes: 0
Reputation: 124646
To accumulate the sum
, change sum = ...
to sum += ...
:
sum += COST[j][j+1];
Btw, I don't know your ultimate goal, but I'm wondering if you might also want to move the int sum = 0
inside the outer for
loop.
Maybe not, it depends on what you're trying to do, this just looks suspicious, that's all, for your consideration.
Upvotes: 1