Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Fisher-Yates Shuffle (was Re: Empty Element)

by Arguile (Hermit)
on Jun 09, 2003 at 05:07 UTC ( #264244=note: print w/ replies, xml ) Need Help??


in reply to Empty Elements

The algorithm from Arithmetic::Numerical::Shuffle is actually the Fischer-Yates shuffle (at least it was last time I checked). For easy reference perlfaq4 answers this question with that same algorithm. Just copy and paste if you want.

The alternate version below was authored by Abigail. It does an inplace shuffle and can take a list as an argument (instead of just an array reference).

sub shuffle { for (my $i = @_; $i;) { my $j = rand $i --; @_ [$i => $j] = @_ [$j => $i] } @_; }

As to your code, two main problems. First of all int(rand($x)) is what you want. Otherwise you get fractional numbers and so appear unique in your %seen hash, but don’t to array subscripts which use them as ints. Next is $DECK[$i] = $1;, what I think you meant is $DECK[$_] = $i. The variable $1 is for regex matching... did you perhaps mean $_?

Either way I’d suggest using the Fisher-Yates shuffle instead, once you’ve ponder it’s workings. It’s a much more efficient method.


Comment on Fisher-Yates Shuffle (was Re: Empty Element)
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (3)
As of 2014-09-23 01:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (210 votes), past polls