I got a little curious about what happens to a deck of cards when you perfect-shuffle it N times, so I wrote some code to do it. I was a bit surprised that so much structure remained in the deck after the fourth shuffle. Stylistic criticism is most welcome.

#! /usr/bin/perl -w use strict; use Data::Dumper; # this is ugly, and overkill sub min { my $x = shift; return $x if scalar @_ == 0; my $y = &min(@_); return $x > $y ? $y : $x; } sub perfect_shuffle { my ($a, $b) = @_; my @res = (); my $n_els = @$a; if(@$a != @$b) { warn "perfect_shuffle: lists must have equal length!\n"; $n_els = &min(scalar @$a, scalar @$b); } while($n_els--) { push @res, shift @$a, shift @$b; } return \@res; } sub build_deck { my $deck = (); for my $suit (('c', 'd', 'h', 's')) { for my $card ((2..9, 'T', 'J', 'Q', 'K', 'A')) { push @$deck, [$suit, $card]; } } return $deck; } sub show_deck { my ($deck) = @_; # print suits, then values # primo candidate for extraction into sub { local $\ = ' '; for (@$deck) { print $_->[0] } } print "\n"; { local $\ = ' '; for (@$deck) { print $_->[1] } } print "\n"; } sub split_deck { my ($deck) = @_; my $mid = @$deck / 2; my @left = @$deck[0..($mid-1)]; my @right = @$deck[$mid..@$deck-1]; return (\@left, \@right); } my $deck = &build_deck(); for my $shuffle (1..10) { print "shuffle $shuffle:\n"; my ($l, $r) = &split_deck($deck); $deck = &perfect_shuffle($l, $r); &show_deck($deck); }

--
F o x t r o t U n i f o r m
Found a typo in this node? /msg me
% man 3 strfry


In reply to Perfectly shuffling a deck of cards, over and over by FoxtrotUniform

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.