Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

RE: Randomize an array

by Adam (Vicar)
on Sep 08, 2000 at 00:14 UTC ( #31475=note: print w/replies, xml ) Need Help??


in reply to Randomize an array

I recommend the Fisher-Yates Shuffle. See my node on the topic.
# The Fisher-Yates Shuffle sub Shuffle { my $arrayref = shift; my $index = @$arrayref; while ( $index-- ) { my $newloc = int rand (1+$i); # next if $index == $newloc; # Not needed in Perl. @$arrayref[$index, $newloc] = @$arrayref[$newloc, $index]; } }
The line I commented out is part of the Fisher-Yates Shuffle, but its a waste of time in Perl, since the swap is done correctly. (If it were an XOR swap then you would want the next in there)

Replies are listed 'Best First'.
Re^2: Randomize an array
by Anonymous Monk on Jul 01, 2008 at 20:56 UTC
    That code has an error and it doesn't actually randomize. Here's the correct version:
    # The Fisher-Yates Shuffle sub Shuffle { my $arrayref = shift; my $index = @$arrayref; while ( $index-- ) { my $newloc = int rand (1+$index); # next if $index == $newloc; # Not needed in Perl. @$arrayref[$index, $newloc] = @$arrayref[$newloc, $index]; } }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2019-05-23 04:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you enjoy 3D movies?



    Results (142 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!