Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: How do I shuffle an array?

by vroom (His Eminence)
on Jan 09, 2000 at 10:02 UTC ( #1905=note: print w/replies, xml ) Need Help??


in reply to How do I shuffle an array?

The Fisher-Yates shuffle is easy to code up:
# randomly permutate @array in place sub fisher_yates_shuffle { my $array = shift; my $i = @$array; while ( --$i ) { my $j = int rand( $i+1 ); @$array[$i,$j] = @$array[$j,$i]; } } fisher_yates_shuffle( \@array ); # permutes @array in place

Replies are listed 'Best First'.
Re: Answer: How do I shuffle an array?
by runrig (Abbot) on Aug 21, 2002 at 16:40 UTC
    And mentioned numerous times in numerous places, the 'next if $i == $j' is unnecessary, as it rarely saves an element swap (except on the smallest of arrays), so it actually costs more to do the comparison every time rather than just swapping unconditionally.

    BTW, in case anyone was wondering who these guys Fisher and Yates were, here's some links. They're hard to find when almost every reference to Fisher and Yates (and especially with the term 'shuffle') on Google is a perl reference :-)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2022-01-23 22:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (64 votes). Check out past polls.

    Notices?