在 Objective-C 中随机化 NSArray 的规范方法 [英] canonical way to randomize an NSArray in Objective-C

查看:16
本文介绍了在 Objective-C 中随机化 NSArray 的规范方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a canonical way to randomize an array in Objective-C?

推荐答案

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

My utility library defines this category on NSMutableArray to do it:

@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)));否则输出不会很随机.

Make sure you seed the random number generator (with e.g. srandom(time(NULL))) sometime before you call it; otherwise the output won't be very random.

这篇关于在 Objective-C 中随机化 NSArray 的规范方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆