Beginning with
private final Card[] deck;
You can do
public void shuffle() {
Cost O (N), where N is the number of random cards.
Imagine you have a small deck, for example
AS AC AD AH 2S 2C 2D 2H
and you need to choose a random first card, you select one of the deck and change it. Say nextInt () 5 => 2C
2C | AC AD AH 2S AS 2D 2H
The table consists of randomly selected cards + not selected. You do not have duplicates, because the same cards are moving. The following random card, for example, 2H, which is replaced by AC
2C 2H | AD AH 2S AS 2D AC
Finally, AD is selected.
2C 2H AD | AH 2S AS 2D AC
This gives you three random cards, and the rest. The same array can be used again, since starting with a sorted or random deck does not make the result more or less random.
In response to the answer, Why does this simple shuffling algorithm produce biased results? if there are 123, possible results
123 +- 123 - swap 1 and 1 (these are positions, not numbers) | +- 123 - swap 2 and 2 | +- 132 - swap 2 and 3 +- 213 - swap 1 and 2 | +- 213 - swap 2 and 2 | +- 231 - swap 2 and 3 +- 321 - swap 1 and 3 +- 321 - swap 2 and 2 +- 312 - swap 2 and 3
As you can see, there are only 6 possible results, all are equally likely.
Peter Lawrey Apr 25 '14 at 12:00 2014-04-25 12:00
source share