I want to shuffle an array of Objects in a card game simulation.
I scrolled through many posts on here and almost all of them mention transforming the array into a list, then shuffling it using an implementation of Collections.shuffle() and then transforming it back into an array.
However, since I actually want to understand what is going on while the shuffling is happening, I want to implement it myself. I wrote this code for my array of Card objects in the array unshuffledDeck[]:
Random shuffleRandom = new Random();
Card[] shuffledDeck = new Card[cardAmount];
for (int i = 0; i < cardAmount; i++) {
int j = (int) (shuffleRandom.nextFloat() * cardAmount);
shuffledDeck[i] = unshuffledDeck[j];
}
However, depending on the random number, multiple entries in the shuffledDeck output array can have the same Card in it, which I don't want.
Now I have thought about just adding an if statement to check if the card is already in one of the other entries, something like
Random shuffleRandom = new Random();
Card[] shuffledDeck = new Card[cardAmount];
for (int i = 0; i < cardAmount; i++) {
int j = (int) (shuffleRandom.nextFloat() * cardAmount);
boolean cardIsNotYetPresent = true;
for (int k = 0; k < cardAmount; k++) {
if (k != i && shuffledDeck[k] == unshuffledDeck[j]) {
cardIsNotYetPresent = false;
break;
}
}
if (cardIsNotYetPresent) {
shuffledDeck[i] = unshuffledDeck[j];
} else {
i--;
}
}
, but that increase the duration drastically, which is not what I want. How would I approach this problem without adding another O(n) to the runtime of the algorithm?
ArrayList(which actually use arrays behind the scenes) orLinkedList(which typically have very poor performance). The main downside is that they're not very versatile in use.