Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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]
[shmem]: but that would mean, also, to drop the "use" not allowed in expression abomination, and make use actually return something useful (as does require at the first call, accidentally)

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (14)
As of 2017-11-21 17:26 GMT
Find Nodes?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:

    Results (306 votes). Check out past polls.