Given below are two algorithms to shuffle a deck of cards:
1 2 3 4 5 6 |
|
1 2 3 4 5 6 |
|
Which method's shuffles are closest to a random shuffling of cards?
Details
random.randrange
is perfectly uniformly random.
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Let me begin with showing some real experimental results to convince you.
This yields:
See? The first algorithm prefers some solutions too much. This could be random, but actually isn't. Let's see why.
Suppose the number of cards is n.
In the first algorithm, the number of available cards between which the swaps are done continually reduces from n to 1. The number of possible sequences of swaps would be n!.
In the second algorithm, the swapping space does not decrease. That would make the number of possible sequences of swaps n^n.
Shouldn't more swaps make things better? Well, it actually makes things worse.
Notice that n^n is greater than n! which happens to be the number of possible permutations. In virtue of the pigeonhole principle, that would mean there would be some permutations which could be reached through more than one sequence of swaps in
bShuffle
. It gets worse since n^n is usually not divisible by n!.It turns out that
aShuffle
is actually foolproof. See the wikipedia entry