in reply to Perfectly shuffling a deck of cards, over and over

This type of shuffle is called a Riffle shuffle. You have enough reading material to satisfy any curiousity about their mathematical properties in the Mathworld entry for Riffle Shuffle and its references (You'll see that it makes a difference if you do an in- or out- shuffle).

japhy has a one-liner to do either-sided Riffle shuffles at Array One-liners. You can make this really succinct if you also use glob to generate the initial deck:

sub riffle { splice @_, @_/2 - $_, 0, pop for 0 .. (@_/2)-1; return @_; } my @deck = glob "{2,3,4,5,6,7,8,9,T,J,K,Q,A}{C,D,H,S}"; for my $shuffle (1 .. 10) { @deck = riffle @deck; print "shuffle #$shuffle:\n@deck\n"; }
It might also be interesting to see what happens when you change the riffle sub to:
## random-sided Riffle shuffle sub riffle { if (rand() < 0.5) { splice @_, @_/2 - $_, 0, pop for 0 .. (@_/2)-1; } else { splice @_, @_/2 + $_, 0, shift for 0 .. (@_/2)-1; } return @_; }

blokhead

Replies are listed 'Best First'.
Re^2: Perfectly shuffling a deck of cards, over and over
by Anonymous Monk on Jul 10, 2004 at 03:03 UTC
    So, why does glob work here when those files most likely don't exist on your system. Skimming through the glob and File::Glob docs it seems like glob should only return valid file names. Its a great trick, and it works for me under Windows. Just curious why?

    Ted

      Like Mr. Muskrat mentioned above, the documentation for glob mentions:

      In list context, returns a (possibly empty) list of filename expansions on the value of EXPR such as the standard Unix shell /bin/csh would do

      So one needs to look to find what the documentation for /bin/csh says. If you search around the web for csh documentation who will come across a section on "filename substitution" (aka globbing). In short what this documentation says is that if it contains a "*", "?","[", or "~" then it an error not to have any files match. On the other hand it mentions nothing of "{".

      It also mentions that something like "a{b,c,d}e" is metanotation for a shorthand way of writing "abe ace ade" which is the trick played above with the glob function to get a list of possible combinations of card values and suits, i.e.,:

      my @deck = glob "{2,3,4,5,6,7,8,9,T,J,K,Q,A}{C,D,H,S}";

      HTH

      -enlil

      It's simple really. The glob documentation says that it performs filename expansion just like the standard Unix shell but it never says that it checks for those files to exist. It's only creating a list of possible filenames. It's up to you to figure out if they are there.