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: 304
CPU Time: 0.00035906 seconds

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

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.