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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |