1

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];
}
reid55
  • 169
  • 3
  • 14
  • No relation to Xcode at all. Retagged. –  Jan 29 '13 at 10:29
  • Yes, I see that, but I don't see how that could cause the problem. – reid55 Jan 29 '13 at 10:38
  • 1
    Are you sure that `tempNSArray` does not contain duplicate elements? – Martin R Jan 29 '13 at 10:43
  • tempNSArray can and does occasionally have duplicate elements. How would that be a problem? In fact, in the situation where the problem occurred, tempNSArray did have duplicate elements, although the element which got erroneously duplicated was not a duplicate a in the original array. – reid55 Jan 29 '13 at 10:45
  • I checked for 100000 number it never repeats....tempNSArray must be unique as said my Martin R. – Anoop Vaidya Jan 29 '13 at 10:47
  • @reid55: `strArray` is a random permutation of `tempNSArray`. It contains the same elements in a different order. If `tempNSArray` has a duplicate element then `strArray` will have the same duplicate element. – Martin R Jan 29 '13 at 10:49
  • @reid55 [This link](http://stackoverflow.com/a/56656/454697) has got exactly what you want. While the way shown in this answer is similar to the way you have done it, there appear to be a few important differences that could make all the difference for you. – Extra Savoir-Faire Jan 29 '13 at 15:22
  • @trudyscousin: The problem I have with the approach used in the link above is that you can never randomize to an index less than the index of the element being randomized. That doesn't seem like a truly random approach to me. – reid55 Jan 29 '13 at 17:16

1 Answers1

1

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];

}
Hmeedo
  • 94
  • 3