Possible Duplicate:
What's t开发者_如何转开发he Best Way to Shuffle an NSMutableArray? Non repeating random numbers
How to get random indexes of NSMutableArray without repeating? I have NSMutableArray *audioList. I want to play each track in shuffle mode, without repeating. How to do this in the best way?
See the code below:
int length = 10; // int length = [yourArray count];
NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:length];
for (int i=0; i<10; i++) [indexes addObject:[NSNumber numberWithInt:i]];
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:length];
while ([indexes count])
{
int index = rand()%[indexes count];
[shuffle addObject:[indexes objectAtIndex:index]];
[indexes removeObjectAtIndex:index];
}
[indexes release];
for (int i=0; i<[shuffle count]; i++)
NSLog(@"%@", [shuffle objectAtIndex:i]);
Now in shuffle you will have indexes of your array without repeating.
Hope, this will help you
Nekto's answer is great, but I would change two things:
1) Instead of using rand(), use arc4random() for less predictable results (more details here):
int index = arc4random() % [indexes count];
2) To output contents of "shuffle", use [myArray description] (no need to use a for loop):
NSLog(@"shuffle array: %@", [shuffle description]);
精彩评论