Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Randomize an array

by BlaisePascal (Monk)
on Sep 08, 2000 at 00:09 UTC ( #31469=note: print w/replies, xml ) Need Help??


in reply to Randomize an array

How random do you want it, and what do you mean by "randomize"? I assume you want a random permutation, all permutations equally likey.

The traditional solution is something like:

for $i ($#array..0) { my $j = rand($i); @array[$i,$j] = @array[$j,$i]; }
This does @array swaps, and can be shown (see Knuth) that all permutations are equally likely -- assuming I haven't made any coding mistakes

This is probably the fastest randomization algorithm, although various implementations might be faster than mine.

Replies are listed 'Best First'.
RE: Re: Randomize an array
by merlyn (Sage) on Sep 08, 2000 at 04:58 UTC
      That's what I get for reading too much of the Perl6 RFCs... I could have sworn that ($high..$low) would count down, not up...

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2019-05-21 17:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you enjoy 3D movies?



    Results (136 votes). Check out past polls.

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