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
The List::Util module provides a shuffle function which implements the Fisher-Yates shuffle.
```use List::Util qw(shuffle);

my @data = (0..51);

my @cards = shuffle @data;
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