iphone - 在 Objective-C 中随机化 NSArray 的规范方法

在 Objective-C 中是否有规范的方法来随机化一个数组?

最佳答案

我的实用程序库在 NSMutableArray 上定义了这个类别来做到这一点:

@interface NSMutableArray (ArchUtils_Shuffle)
- (void)shuffle;
@end

// Chooses a random integer below n without bias.
// Computes m, a power of two slightly above n, and takes random() modulo m,
// then throws away the random number if it's between n and m.
// (More naive techniques, like taking random() modulo n, introduce a bias 
// towards smaller numbers in the range.)
static NSUInteger random_below(NSUInteger n) {
    NSUInteger m = 1;

    // Compute smallest power of two greater than n.
    // There's probably a faster solution than this loop, but bit-twiddling
    // isn't my specialty.
    do {
        m <<= 1;
    } while(m < n);

    NSUInteger ret;

    do {
        ret = random() % m;
    } while(ret >= n);

    return ret;
}

@implementation NSMutableArray (ArchUtils_Shuffle)

- (void)shuffle {
    // http://en.wikipedia.org/wiki/Knuth_shuffle

    for(NSUInteger i = [self count]; i > 1; i--) {
        NSUInteger j = random_below(i);
        [self exchangeObjectAtIndex:i-1 withObjectAtIndex:j];
    }
}

@end

确保在调用之前的某个时间为随机数生成器播种(例如 srandom(time(NULL)));否则输出不会很随机。

https://stackoverflow.com/questions/791232/

相关文章:

objective-c - 如何在没有 Interface Builder 的情况下创建 Cocoa

iphone - 如何以编程方式区分 iphone 4 和 iphone 4S?

objective-c - 在 ARC 之后,我应该为调度队列使用什么属性?

ios - 使用钩子(Hook)在 Instagram 上发布视频

ios - 呈现模态视图 Controller 的延迟

objective-c - 在 mac 包中嵌入字体

objective-c - 滚动 NSScrollView 时的回调?

objective-c - NSMutableDictionary 线程安全

iphone - 从 float 或 double 实例化 NSDecimalNumber 的正确方

c - 在 Objective-C 类中混合 C 函数