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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Perfectly shuffling a deck of cards, over and over
by blokhead (Monsignor) on Jul 10, 2004 at 00:35 UTC | |
by Anonymous Monk on Jul 10, 2004 at 03:03 UTC | |
by Enlil (Parson) on Jul 10, 2004 at 05:31 UTC | |
by Mr. Muskrat (Canon) on Jul 10, 2004 at 04:45 UTC | |
|
Re: Perfectly shuffling a deck of cards, over and over
by Discipulus (Canon) on Jul 12, 2004 at 09:24 UTC | |
by QM (Parson) on Jul 12, 2004 at 13:45 UTC | |
by ChuckularOne (Prior) on Jul 23, 2004 at 12:03 UTC | |
|
Re: Perfectly shuffling a deck of cards, over and over
by spurperl (Priest) on Jul 11, 2004 at 17:08 UTC |