How to really shuffle a deck of cards
When I need to shuffle a deck of poker cards in Java/Android, I use , of course. I've ever been doing this and the results seemed acceptable. But they aren't.Collections.shuffle(List<?> list)
As outlined in this paper, there are 52! possible unique shuffles of a 52 card poker deck. That amounts to about 2^226.
But uses by default which uses a 48-bit seed and can therefore only create 2^48 unique shuffles - which is only percent of all possible shuffles!Collections.shuffle(List<?> list)
new Random()
3.49*10^(-52)
So how do I shuffle cards the right way?
I've started using , but is that enough, finally?SecureRandom
List<Card> cards = new ArrayList<Card>();
...
SecureRandom secureRandom;
try {
secureRandom = SecureRandom.getInstance("SHA1PRNG");
}
catch (NoSuchAlgorithmException e) {
secureRandom = new SecureRandom();
}
secureRandom.nextBytes(new byte[20]); // force SecureRandom to seed itself
Collections.shuffle(cards, secureRandom);