I am trying to shuffle a deck of cards in my application and I am using the following code. Will it be enough to randomize the deck? I am pretty sure this is just a desire for a different opinion. Thank!
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 someone wonders or should run into this in the future. This is what I went to shuffle the deck of cards, this is the implementation of the Fisher-Yate algorithm. I got it from the @MartinR post suggested below, which can be found here: What is the best way to swap in NSMutableArray?
NSUInteger count = [deck.cards count];
for (uint i = 0; i < count; ++i)
{
int nElements = count - i;
int n = arc4random_uniform(nElements) + i;
[deck.cards exchangeObjectAtIndex:i withObjectAtIndex:n];
}
source
share