[Kc] Shuffling a deck of cards...
David Nicol
davidnicol at gmail.com
Wed Apr 2 18:57:56 PDT 2008
> > > > My instructor has asked me to use the pop, shift, and push functions
> to write a script that sufficiently "shuffles" a simulated deck of cards
> before printing the top five cards.
Here's a model of shuffling, like, err, shuffling.
use strict;
my @deck = qw/a b c d e f g h i j k l m n o p q r s t u v w x y z A B
C D E F G H I J K L M N O P Q R S T U V W X Y Z/;
my @right;
my @left;
SHUFFLE:
unshift @left, pop @deck for 1..26;
@right = @deck;
@deck = ();
while(@left or @right){
if (rand() < 0.5){
@left and push @deck, shift @left
}else{
@right and push @deck, shift @right
}
};
# shuffle again?
rand() < 0.9 and goto SHUFFLE;
print "the top five cards are @deck[0..4]\n";
__END__
# shuffle again?
rand() < 0.9 and goto SHUFFLE;
print "the top five cards are @deck[0..4]\n";
__END__
More information about the kc
mailing list