Shuffle NSMutableArray objective-c

Tim*_*aev 3 random shuffle objective-c nsmutablearray

可能重复:
什么是洗牌NSMutableArray的最佳方式?
非重复随机数

如何获取NSMutableArray的随机索引而不重复?我有NSMutableArray*audioList.我想以随机模式播放每首曲目,而不重复.如何以最好的方式做到这一点?

Nek*_*kto 5

请参阅以下代码:

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]);
Run Code Online (Sandbox Code Playgroud)

现在在shuffle中你将拥有你的数组的索引而不重复.

希望对你有帮助