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

倾然丶 夕夏残阳落幕 提交于 2019-12-01 23:46:22

问题


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:


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



来源:https://stackoverflow.com/questions/37474819/c-how-should-i-go-about-shuffling-contents-of-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!