Quote:
Originally Posted by Jez
Hi guys,
i am working right now on a little game. To figure out who won at the end I am using a couple of loops to find out who got the highest score. The problem is, if i got 2 or more winners.
Here is the code:
Code:
int maxValue = 0;
for (NSNumber *number in scores)
{
int currentValue = [number intValue];
if (currentValue > maxValue)
maxValue = currentValue;
}
NSLog(@"%d", maxValue);
//END
NSMutableArray *winners = [[NSMutableArray alloc] init];
int playerNum;
NSUInteger winnerIndex = 0;
for (int x = 0; x < 4; x++) {
if ([scores containsObject:[NSNumber numberWithInt:maxValue ]]) {
winnerIndex = [scores indexOfObject:[NSNumber numberWithInt:maxValue]];
[scores removeObjectAtIndex:winnerIndex];
playerNum = winnerIndex + 1;
NSLog(@"%d", playerNum);
[winners addObject:[NSString stringWithFormat:@"Player %d", playerNum]];
}
}
for (NSString *winWin in winners){
NSLog(@"%@", winWin);
}
[winners release];
If just 1 person wins, it works just fine, but if its a draw I get player 1 twice in the output. It has to be obvious but I can't see it...
|
That's a seriously complicated way to do something really simple. So, wow, right there
Anyway, your problem is that you are changing your "scores" array and at the same time as you try to use the indexes into it to determine the player number. For example, say you have two scores, both "6."
So, maxValue = 6. index 0 of scores is equal to 6. So, you put "player 1" into your winners array. BUT, you also remove index 0. Now "scores" has only one score in it, 6, because you removed the first 6. Index 0 of scores is equal to 6. So, you put "player 1" into your winners array again, and now "scores" is empty.
I don't know why you are looping four times using "x" and not using "x" in the loop body, or why you are removing from "scores" while looking in it, but I'm pretty sure that is the cause of your unexpected output.
I would just loop scores and record each player index that has the same value as maxValue. Use an indexed loop (i=0;i<[scores count];i++) and in the body just check [scores objectAtIndex:i] to see if it equals maxValue. If it does, add "Player i+1" to your winners list and move on. If you did that in my example above, when you're done Winners will have "Player 1" and "Player 2." If you need to clear "scores" just do [scores removeAllObjects]