jeudi 26 mai 2016

How should I go about shuffling contents of an array?

I have an array of integers called cards[52]. Each element contains an integer that represents a card (cards[0] = 5 would represent the 6 of clubs for example).

This is how I shuffled the array. It works, but I am getting repeats.

private void shuffleCards()
    {
        for (int i = 0; i < cards.Length; i++)
        {
            int randIndex = r.Next(0, 52);
            int origCard = cards[i];
            cards[i] = cards[randIndex];
            cards[randIndex] = origCard;
        }
    }

r is the Random variable I initialized in the beginning of the program.

When testing the program, I noticed I would get the same card 2 or 3 times. Obviously I cannot get repeats, they all must be different. I can't see in any way how this method gives me repeats.

How can I shuffle this array without any repeats? Thanks.




Aucun commentaire:

Enregistrer un commentaire