Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://264244]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (9)
As of 2017-09-25 11:57 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (280 votes). Check out past polls.