我想洗牌的我的应用程序一副牌,我用下面的code。这是否会充分随机甲板?我几乎可以肯定是会只是想另一种意见。谢谢!
的for(int i = 0; I< 40000;我++){
INT randomInt1 = arc4random()%[deck.cards计数]
INT randomInt2 = arc4random()%[deck.cards计数]
[deck.cards exchangeObjectAtIndex:randomInt1 withObjectAtIndex:randomInt2]。
编辑:如果你想知道或者应该碰到过这样的未来。这是我已经与洗牌我的扑克牌,它是费雪耶茨算法的实现。我把它从后@MartinR建议低于它可以在这里找到:What's最好的方式来洗牌一个NSMutableArray?
NSUInteger数= [deck.cards计数]
对于(UINT I = 0; I<计数; ++ I)
{
//我和阵列交换与端之间选择一个随机元素。
INT nElements =计数 - 我;
INT N = arc4random_uniform(nElements)+ I;
[deck.cards exchangeObjectAtIndex:我withObjectAtIndex:N];
}
解决方案
您code应该相当不错,如果[deck.cards算上] LT; 40000,但下面是更好的。
的for(int i = [deck.cards数] - 1; I> 0;我 - ){
INT randomInt1 = arc4random_uniform第(i + 1);
[deck.cards exchangeObjectAtIndex:randomInt1 withObjectAtIndex:我]。
}
从文档:
arc4random_uniform()将返回一个均匀分布的随机数 比UPPER_BOUND少。 arc4random_uniform()建议在结构像``arc4random()%UPPER_BOUND'',因为它避免了 模数偏差时的上限不是二的幂。
I am trying to shuffle a deck of cards in my app and I use the following code. Will this sufficiently randomize the deck? I am almost certain is will just want another opinion. Thanks!
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];
EDIT: In case anyone is wondering or should come across this in the future. This is what I have gone with to shuffle my deck of cards, it is an implementation of the Fisher-Yates Algorithm. I got it from the post @MartinR suggested below which can be found here: What's the Best Way to Shuffle an 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];
}
解决方案
Your code should work rather good if [deck.cards count] < 40000 but following is better
for (int i = [deck.cards count] - 1; i > 0 ; i--) {
int randomInt1 = arc4random_uniform(i + 1);
[deck.cards exchangeObjectAtIndex:randomInt1 withObjectAtIndex:i];
}
from docs:
arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.