Is this a good way to shuffle a deck of cards?

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)
    {
        // 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];
    }
+4
source share
2 answers

, [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];
}

:

arc4random_uniform() , upper_bound.      arc4random_uniform() , `` arc4random()% upper_bound '',       "modulo bias", .

+7

-. , , , !

NSUInteger count = [deck.cards count];
if (count > 0) {
    for (NSUInteger i = count - 1; i > 0 ; --i) {
        [deck.cards exchangeObjectAtIndex:i
                        withObjectAtIndex:arc4random_uniform(i + 1)];
    }
}
+3

Source: https://habr.com/ru/post/1538767/


All Articles