Search code examples
javaarraylistrandomplaying-cards

Randomness of shuffled cards


I have an Array List of cards containing 52 cards. I want to shuffle the deck.

This is what I have done.

  1. Created a new Array List.
  2. Generated random index between 0 to deck size.
  3. Get card at random index and add to new list.
  4. Remove card from deck
  5. Repeat until deck is empty.

Here is my code:

String[] Number = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
String[] Suits = {"Club","Diamonds","Hearts","Spades"};
ArrayList<Card> deck = new ArrayList<Card>();

// create a deck    

for(int i=0;i<13;i++){
        for(int j=0;j<4;j++){
            Card card = new Card(Suits[j],Number[i]);
            deck.add(card);
        }    
    }

// shuffle of deck

ArrayList<Card> new_deck = new ArrayList<Card>();
    while(deck.size()!=0){   

        Random rand = new Random();
        int  n = rand.nextInt(deck.size());

        new_deck.add(deck.get(n));
        deck.remove(n);
    }

// Display

for(int i=0;i<52;i++){
        System.out.println(new_deck.get(i).getSuit()+" : "+new_deck.get(i).getValue());
    }

Finally, I get the shuffled deck from new ArrayList.

Is its randomness good enough or not?

What should I do to increase randomness?


Solution

  • Does it's randomness is enough or not ?

    Define good enough (!!)

    Your current approach is going to give a good shuffle, with no obvious biases ... except for biases that may be introduced by the random number generator.

    And in this case, there is real cause for concern. Random is specified to be a linear congruential generator, and LC generations have distinct patterns in the numbers that they generate. (In statistical terms, they show strong auto-correlation.) This is quite clear if you graph the n'th random number against n.

    To improve randomness, you should use a better random number generator. The SecureRandom generator should be good enough: javadoc.


    The same concern about the randomness applies if you use Collections.shuffle method. For a good (or consistent) shuffle you should use the method overload where you supply a Random implementation ... and choose a good one.