1

I've read many things on the topic, but I am still having misgivings about it. Please, help!

I create a deck of 52 cards:

int[] deck = new int[52]; 
for (int i = 0; i < deck.length; i++) {deck[i] = i;}

Now, I'd like to shuffle the deck properly, not by following any pattern or function.

I am going to use the Math.random() method in my algorithm:

for (int i = 0; i < deck.length; i++) {
    int j = (int)(Math.random() * deck.length); // Get a random index out of 52
    int temp = deck[i]; // Swap the cards
    deck[i] = deck[j];
    deck[j] = temp;
}

The problem I am having here, however, is that I sometimes might get duplicates; as a result, some cards/values are missing altogether.

I am almost certain that I am not discarding the indices/values I have already used, which is probably the core of the abovementioned problem. But how do I go about it?

Any suggestions? Possibly, following my same train of thought. Thanks a bunch!

screenshot 1

screenshot 2

Illy P.
  • 11
  • 1
  • 1
  • 4

2 Answers2

5

Simply use a new array for the shuffled cards and fill it using random cards removed from the prior array.

import java.util.ArrayList;

public class Test {
    private static final int DECK_SIZE = 52;

    public static void main(String args[]) {
        ArrayList<Integer> deck = new ArrayList<Integer>();

        for (int i = 0; i < DECK_SIZE; ++i) {
            deck.add(i);
        }

        ArrayList<Integer> shuffledDeck = new ArrayList<Integer>();

        while (deck.size() > 0) {
            int index = (int) (Math.random() * deck.size());
            shuffledDeck.add(deck.remove(index));
        }

        System.out.println(shuffledDeck.toString());
    }
}

Or just use Collections.shuffle():

import java.util.ArrayList;
import java.util.Collections;

public class Test {
    private static final int DECK_SIZE = 52;

    public static void main(String args[]) {
        ArrayList<Integer> deck = new ArrayList<Integer>();

        for (int i = 0; i < DECK_SIZE; ++i) {
            deck.add(i);
        }

        Collections.shuffle(deck);

        System.out.println(deck);
    }
}
felipeptcho
  • 1,377
  • 2
  • 9
  • 23
0

Please look if this helps:

boolean init[] = new boolean[52];
Random r = new Random();

int getNextCard(){
    int i = r.nextInt(52);
    while(init[i])
        i = r.nextInt(52);
    init[i] = true;
    return i;
}

void shuffleCards() {   

    int[] deck = new int[52];
    for (int i = 0; i < deck.length; i++) {
        deck[i] = getNextCard();
    }
    System.out.println(Arrays.toString(deck));
}

Idea is to use a Random to generate a random number between 0 and 52. Once a number is taken, we will mark it as taken in the boolean array init.So, next time the same number comes up, we again generate the random number until we get a number we haven't already taken.

Fayaz
  • 461
  • 2
  • 7