Reputation: 169
I have an array that I am randomizing. I have not been able to re-produce this, but a user of my app has reported that he experienced a situation where one of the elements of the array occurred twice and another one did not occur at all. Looking at the logic below, is there anything about it which might cause that problem in certain situations?
NSMutableArray *strArray = [NSMutableArray arrayWithCapacity:18];
[strArray addObjectsFromArray:tempNSArray];
int randomIndex, arrayCount = [strArray count];
for (int i = 0; i < arrayCount; i++) {
randomIndex = arc4random() % arrayCount;
[strArray exchangeObjectAtIndex:i withObjectAtIndex:randomIndex];
}
Upvotes: 1
Views: 60
Reputation: 94
try to to make new NSMutableArray with contents of array tempNSArray and when you choose a random object remove it untill the new NSMutableArray is empty. try this code :
NSMutableArray *strArray = [[NSMutableArray alloc]init];
NSMutableArray *tempMutableArray=[[NSMutableArray alloc]initWithArray:tempNSArray];
int randomIndex;
while ([tempMutableArray count]=!0){
randomIndex = arc4random() % [tempMutableArray count];
[strArray addObject:[tempMutableArray objectAtIndex:randomIndex]];
[tempMutableArray removeObjectAtIndex:randomIndex];
}
Upvotes: 1