【问题标题】:Shuffle the content in a NSMutableArray [duplicate]随机播放 NSMutableArray 中的内容 [重复]
【发布时间】:2012-04-15 11:32:29
【问题描述】:

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

我在NSMutableArray 中有一些值。现在我需要洗牌这些值。谁能告诉我如何改组这些值。

抱歉,我没有要演示的代码。

我浏览了这个SO 帖子,建议使用exchangeObjectAtIndex:withObjectAtIndex:,但有人可以告诉我它是如何完成的。解释这一点的示例或教程会有所帮助。

【问题讨论】:

  • 您为什么不查看该问题的其他答案? One of them 提供完整的解决方案。

标签: iphone objective-c


【解决方案1】:

你可以这样做:

for (int i = [array count] - 1; i > 0; i--) {
    int j = arc4random() % (i+1);
    [array exchangeObjectAtIndex:i withObjectAtIndex:j];
}

数组是你的NSMutableArray

【讨论】:

  • 为了获得良好的随机播放效果,您不想使用array count 而是使用i 进行调制。见the Fisher-Yates shuffle‌​
  • @SSteve 你是对的!谢谢,我更新了答案。
猜你喜欢
  • 2011-11-10
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-16
  • 2017-11-11
相关资源
最近更新 更多