I'm working on a statistics project involving cards and shuffling, and I've run across an issue with random number generation.
From a simple bit of math there are 52! possible deck permutations, which is approximately 2^226. I believe this means that I need a random number generator with a minimum of 226 bits of entropy, and possibly more (I'm not certain of this concept so any help would be great).
From a quick google search, the Math.random() generator in Java has a maximum of 48 bits of entropy, meaning that the vast majority of possible deck combinations would not be represented. So this does not seem to be the way to go in Java.
I was linked to this generator but it doesn't have a java implementation yet. Also for a bit of context here is one of my shuffling algorithms (it uses the Fisher-Yates method). If you have any suggestions for better code efficiency that would be fantastic as well.
public void shuffle(int type, int swaps){
int[] newDeck = getNewDeck();
if(type == 1){
for(int i = 0; i < 52; i++){
int nextCardIndex = (int)(Math.random()*newDeck.length);
deck[i] = newDeck[nextCardIndex];
newDeck = removeItem(nextCardIndex, newDeck);
}
}
}
public int[] getNewDeck(){
int[] newDeck = new int[52];
for(int i = 1; i <= 52; i++){
newDeck[i-1] = i;
}
return newDeck;
}
public int[] removeItem(int index, int[] array){
int[] newArray = new int[array.length-1];
for(int i = 0; i < index; i++){
newArray[i] = array[i];
}
for(int i = index; i < array.length-1; i++){
newArray[i] = array[i+1];
}
array = newArray;
return array;
}
Have you looked into the recent additions that are included in JDK 17?
There are plenty of algorithms available:
For shuffling cards you likely don't need something that is cryptographically secure.
Using Collections.shuffle should do the trick if you provide a decent RNG.