Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

How do I shuffle an array?

by vroom (Pope)
on Jan 08, 2000 at 08:19 UTC ( #1869=perlquestion: print w/replies, xml ) Need Help??

vroom has asked for the wisdom of the Perl Monks concerning the following question: (arrays)

How do I shuffle an array?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I shuffle an array?
by hossman (Prior) on Jun 15, 2003 at 22:50 UTC
      I prefer japhy's one-liner, which achieves shuffling via fisher-yates:

      @entry[-$i,$j] = @entry[$j,-$i] while $j = rand(@entry - $i), ++$i < @ +entry;
      as an aside - this is in the snippets section. would it not be nice to use snippets, or grinder's fabled categorized snippets library, as a source of data for categorized q&a?

      ttfn,

      ...wufnik

      -- in the world of the mules there are no rules --
      Independet way:
      my @data = 0..51; my @cards = sort { (-1,1)[rand(2)] } @data ;

      Graciliano M. P.
      "The creativity is the expression of the liberty".

      Math::Random::MT::Auto has a shuffle function, as well:
      use Math::Random::MT::Auto 'shuffle'; my @cards = 0..51; shuffle(\@cards);

      Remember: There's always one more bug.
Re: How do I shuffle an array?
by vroom (Pope) on Jan 09, 2000 at 10:02 UTC
    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
      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: perlquestion [id://1869]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (1)
As of 2021-10-23 15:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (88 votes). Check out past polls.

    Notices?