in reply to What I am missing here
First step is a better shuffle algorithm, which is right there in Recipe 14.7, the fisher-yates algorithm. I don't see the need to keep the suits separate, generate an array (or just type it in manually) with all 52 cards, shuffle and away you go!
#!/usr/bin/perl -w use strict; use Data::Dumper; my @deck = make_deck(); fisher_yates_shuffle(\@deck); #in place shuffle print Dumper \@deck; # use pop or shift of @deck to deal a single card # or perhaps use splice to deal out multiple cards # the cards are already randomized so it doesn't matter # how you deal 'em. my @deal4 = splice(@deck,0,4); print "4 cards: @deal4\n"; #4 cards: 6_heart 9_heart J_heart Q_spade # From Perl Cookbook Recipe 14.7 # Randomizing an Array with fisher_yates_shuffle sub fisher_yates_shuffle { my $array = shift; my $i; for ($i = @$array; --$i; ) { my $j = int rand ($i+1); next if $i == $j; @$array[$i,$j] = @$array[$j,$i]; } } sub make_deck #or just use a fixed array with 52 cards { my @cards = ( 2,3,4,5,6,7,8,9,10,'J','Q','K','A'); my @deck; foreach my $suit qw(spade diamond heart club) { push @deck, map{"$_"."_$suit"}@cards; } return @deck; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: What I am missing here
by heatblazer (Scribe) on Mar 21, 2012 at 09:33 UTC |