Is there such a beast as a "perfect" shuffle? :)

Christopher Browne cbbrowne at acm.org
Fri May 10 16:09:18 EDT 2002


Tim Peters <tim.one at comcast.net> wrote:
> [Christos Georgiou]
>> ...
>> Apart from that, which is just a naive approach, any hints / clues for
>> building good, uniform random numbers in the range 52! ?
>
> This is difficult.  Here's one way:
>
> http://www.faqts.com/knowledge_base/view.phtml/aid/4406/fid/546

The basic principle is to make sure that you run through them all and
give opportunity for them to get swapped into any position.

The unbiased way is not quite intuitive...

- You run through from position 1 to position 52

- For each position, select a random location from [present] to
  the end of the list.

- Swap what's in the current location with the contents of that other
  random location.

The nonintuitive part is that the random range shrinks as you move
along.  If you leave the range open, there's a bit of a bias.  It's a
significant bias, if there are only 3 cards.  It's not nearly so
significant with 52.

You could do far worse than running through the 52 locations and, for
each one, swap it with a randomly selected location.  That will
certainly shuffle things about pretty decently.
-- 
(concatenate 'string "chris" "@cbbrowne.com")
http://www.cbbrowne.com/info/rdbms.html
A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe,
percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again
(or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore
hats, a peon, a canal--Panama!



More information about the Python-list mailing list