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

RE: Randomize an array

by BlueLines (Hermit)
on Sep 08, 2000 at 00:10 UTC ( #31470=note: print w/replies, xml ) Need Help??


in reply to Randomize an array

Here's what the Cookbook offers for randomizing arrays:
<br><br># fisher_yates_shuffle( \@array ) : generate a random permutat +ion # of @array in place sub fisher_yates_shuffle { my $array = shift; my $i; for ($i = @$array; --$i; ) { my $j = int rand ($i+1); next if $i == $j; @$array[$i,$j] = @$array[$j,$i]; } } fisher_yates_shuffle( \@array ); # permutes @array in place
BlueLines

Disclaimer: This post may contain inaccurate information, be habit forming, cause atomic warfare between peaceful countries, speed up male pattern baldness, interfere with your cable reception, exile you from certain third world countries, ruin your marriage, and generally spoil your day. No batteries included, no strings attached, your mileage may vary.

Replies are listed 'Best First'.
RE: RE: Randomize an array
by Anonymous Monk on Sep 09, 2000 at 02:03 UTC
    The 'next if..' line in this post, and the 'unless ...' clause in the next post are unneccessary, and slow the algorithm down for an array of ~20 elements or larger.

    This is because if you assume the cost of a comparison is 1, and the cost of a swap is ~10, then when $i > 10, the savings on a swap are lost because odds are < 1 in 10 that you're swapping the same element. Benchmark comparison against swapping, and do the math. YMMV.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2019-07-19 09:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?