Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: What I am missing here

by Marshall (Canon)
on Mar 20, 2012 at 20:37 UTC ( [id://960650]=note: print w/replies, xml ) Need Help??


in reply to What I am missing here

I looked in my copy of "The Perl Cookbook" a very, very handy critter to have around and highly recommended by me. There are all sorts of solutions to common problems - well worth the money.

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

    I know about that algorithm, better say 'heard' than 'know', actually, but really I think that it`s a bit complex for a simple task like mine, not that is bad or good, it`s just another way to do it. Maybe I would have used it if I know how to implement it, but since I don`t have that cookbook, I just made my own ( simple as it is ). However, thanx for the recipe, if I am going to make a real game ( sallable ) will consider Yates shuffle algorithm

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://960650]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-04-26 01:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found