如何获取NSMutableArray的随机索引而不重复?
我有一个NSMutableArray *audioList。我想在随机模式下播放每个音轨,而不重复。最好的方法是什么?
可能重复:如何对NSMutableArray进行最佳洗牌?
非重复随机数
可能重复:如何对NSMutableArray进行最佳洗牌?
非重复随机数
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]);
int index = arc4random() % [indexes count];
NSLog(@"shuffle array: %@", [shuffle description]);
NSLog(@"shuffle array: %@", shuffle);
等同于 NSLog(@"shuffle array: %@", [shuffle description]);
,因为 %@
发送消息 description
给对象。 - PengOne