这是否足以让一副纸牌洗牌?

mat*_*n88 4 algorithm shuffle objective-c ios

我试图在我的应用程序中洗牌,我使用以下代码.这会使甲板充分随机化吗?我几乎肯定会只是想要另一种意见.谢谢!

for (int i = 0; i < 40000; i++) {
    int randomInt1 = arc4random() % [deck.cards count];
    int randomInt2 = arc4random() % [deck.cards count];
    [deck.cards exchangeObjectAtIndex:randomInt1 withObjectAtIndex:randomInt2];
Run Code Online (Sandbox Code Playgroud)

编辑:如果有人想知道或将来会遇到这个问题.这就是我用去洗牌的方式,它是Fisher-Yates算法的一个实现.我从下面提到的@MartinR帖子中得到了它,可以在这里找到:什么是洗牌NSMutableArray的最佳方法?

NSUInteger count = [deck.cards count];
    for (uint i = 0; i < count; ++i)
    {
        // Select a random element between i and end of array to swap with.
        int nElements = count - i;
        int n = arc4random_uniform(nElements) + i;
        [deck.cards exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
Run Code Online (Sandbox Code Playgroud)

Avt*_*Avt 7

如果[deck.cards count] <40000,你的代码应该工作得相当好,但是后续更好

for (int i = [deck.cards count] - 1; i > 0 ; i--) {
    int randomInt1 = arc4random_uniform(i + 1);
    [deck.cards exchangeObjectAtIndex:randomInt1 withObjectAtIndex:i];
}
Run Code Online (Sandbox Code Playgroud)

来自docs:

arc4random_uniform()将返回小于upper_bound的均匀分布的随机数.arc4random_uniform()建议使用像``arc4random()%upper_bound''这样的结构,因为当上限不是2的幂时,它避免了"模偏差".