C#: How should I go about shuffling contents of an

2019-02-25 01:50发布

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.

EDIT

Okay, turns out the shuffle function wasn't the problem. It is the deal() function that is causing the problem.

private void deal()
    {
        for (int i = 0; i < 26; i++)
        {
            userCards[i] = cards[i];
            setUserValue(); //ignore this
        }
        for (int i = 26; i < 52; i++)
        {
            opponentCards[i - 26] = cards[i];
            setOpponentValue(); //ignore this
        }
    }

I know for sure it isn't the shuffle function. I printed the results of all the cards to a text file and saw no iterations. However, when the cards are dealt to the user and the opponent, that's when all the iterations occur. Any advice?

1条回答
劳资没心,怎么记你
2楼-- · 2019-02-25 02:20

There is very simple algorithm known as Fisher Yates shuffling algorithm which does the shuffling in O(n) time and O(1) space complexity.

Use a random function that generates a random index from the given set and replace the random element generated with the last index. Decrement last index and continue like this for the rest of elements.

Let the array of size n be : arr[n]

void randomize ( int arr[], int n )
{
    // Use a different seed value so that we don't get same
    // result each time we run this program
    srand ( time(NULL) );

    // Start from the last element and swap one by one. We don't
    // need to run for the first element that's why i > 0
    for (int i = n-1; i > 0; i--)
    {
        // Pick a random index from 0 to i
        int j = rand() % (i+1);

        // Swap arr[i] with the element at random index
        swap(&arr[i], &arr[j]);
    }
}

Source : Algorithm

查看更多
登录 后发表回答