Shuffle Cards

This simplem exercise was to find a simple, reliable way to shuffle a deck of cards. Obviously, the rules include: all cards must be used, no card may be used more than once, cards should be random selected and have an equal chance of being selected, and code should be both efficient and concise.

The original goal was to write just a little code to get to the goal, but I actually found it was faster to just iterate through the deck until I found working combos. The ideal result is that number of iterations needed below is as close to 52 as possible (it usually takes between 190-350 times), but also keep an eye on the time needed (usually between 0.003 and .005 seconds, which includes generating the text).

The source for this script can be found at shuffle.phps.

Each time you reload the page, the deck reshuffles! (try again)

Iterations: 364
CPU Time: 0.0007031 seconds

1) 3H
2) 4D
3) 4S
4) 5H
5) 7D
6) 8S
7) KS
8) JD
9) AC
10) 10C
11) 6H
12) 9H
13) JS
14) 2H
15) 5S
16) KH
17) 9S
18) 5D
19) 3S
20) 3C
21) 6S
22) 4H
23) AD
24) 10D
25) 7H
26) QC
27) 10S
28) 7S
29) 3D
30) 9D
31) 8H
32) 10H
33) QD
34) 6C
35) QH
36) AS
37) 8D
38) 7C
39) 2S
40) KC
41) 6D
42) JC
43) 9C
44) 2C
45) AH
46) KD
47) QS
48) 2D
49) 8C
50) 4C
51) JH
52) 5C

This site is powered by Free Software, including Linux, Apache, MySQL, PHP, and Small Axe.
Source Code © 2002-2006, Adam Scheinberg unless otherwise noted.
Content may not be reprinted without permission
Syndicate my blog via: RSS or Atom.