【发布时间】:2010-09-08 13:41:53
【问题描述】:
如果你有NSMutableArray,你如何随机打乱元素?
(对此我有自己的答案,发布在下面,但我是 Cocoa 的新手,我很想知道是否有更好的方法。)
更新:正如@Mukesh 所指出的,从 iOS 10+ 和 macOS 10.12+ 开始,有一个 -[NSMutableArray shuffledArray] 方法可用于随机播放。有关详细信息,请参阅https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc。 (但请注意,这会创建一个新数组,而不是在原地打乱元素。)
【问题讨论】:
-
看看这个问题:Real-world problems with naive shuffling 关于你的洗牌算法。
-
这是 Swift 中的一个实现:iosdevelopertips.com/swift-code/swift-shuffle-array-type.html
-
目前最好的是Fisher-Yates:
for (NSUInteger i = self.count; i > 1; i--) [self exchangeObjectAtIndex:i - 1 withObjectAtIndex:arc4random_uniform((u_int32_t)i)]; -
各位,来自iOS 10++的new concept of shuffle array苹果给的,看this answer
-
现有
API的问题是它返回一个新的Array,该地址指向内存中的新位置。
标签: objective-c cocoa shuffle