【问题标题】:Shuffle NSMutableArray objective-c [duplicate]随机播放 NSMutableArray 目标-c [重复]
【发布时间】:2011-11-10 13:18:17
【问题描述】:

可能重复:
What's the Best Way to Shuffle an NSMutableArray?
Non repeating random numbers

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

【问题讨论】:

标签: objective-c random nsmutablearray shuffle


【解决方案1】:

Nekto 的回答很棒,但我会改变两点:

1) 不要使用 rand(),而是使用 arc4random() 以获得更不可预测的结果(更多详细信息 here):

int index = arc4random() % [indexes count];

2) 输出“shuffle”的内容,使用[myArray描述](不需要使用for循环):

NSLog(@"shuffle array: %@", [shuffle description]);

【讨论】:

  • 为了进一步简化,调用NSLog(@"shuffle array: %@", shuffle); 等效于NSLog(@"shuffle array: %@", [shuffle description]);,因为%@ 将消息description 发送到对象。
【解决方案2】:

请看下面的代码:

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

现在在 shuffle 中,您将拥有数组的索引而无需重复。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2012-04-15
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    相关资源
    最近更新 更多