Question

Here is the problem description:

"The shuffle method shuffles the array of Card objects by looping through the array of Card objects one position at a time and exchanging (see slides 62-63 of the array lecture) the Card in that position with the Card in a random position (as determined by a Random number) between 0 and 51."

I've written the below code to do the above, but it's not shuffling my card objects.

public void shuffle()
{
    //reset nextCard to 0.
    nextCard = 0;

    Random randomGen = new Random();
    Card tempCard;

    int randomNum = randomGen.nextInt(DECK_SIZE);

    int i;
    for(i=0;i<DECK_SIZE;i++)
    {
        tempCard = deck[i];
        deck[i] = deck[randomNum];
        deck[randomNum] = tempCard;
    }//end for.
}//end shuffle().

What's the problem and how do I fix it?

P.S. I will post console output upon request.

Was it helpful?

Solution

You should generate randomNum for each iteration of the for loop

Rewriting your loop like this will give you expected result,

int randomNum;
int i;
for(i=0;i<DECK_SIZE;i++)
{
    randomNum = randomGen.nextInt(DECK_SIZE);
    tempCard = deck[i];
    deck[i] = deck[randomNum];
    deck[randomNum] = tempCard;
}//end for.

OTHER TIPS

The method of @Karthik is incorrect because it uses randomGen.nextInt(DECK_SIZE) which returns a number [0..DECK_SIZE-1] each time. What you really want is to swap DECK[i] with one of the values [DECK[i+1]..DECK[N-1]] which is one of the remaining values not yet used. This is called the Knuth shuffle.

public static void shuffle(int[] a)
{
    int N = a.length;
    for (int i = 0; i < N; i++)
    { // Exchange a[i] with random element in a[i..N-1]
        int r = i + StdRandom.uniform(N-i);
        int temp = a[i];
        a[i] = a[r];
        a[r] = temp;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top