For Programmers: Free Programming Magazines  


Home > Archive > PERL Miscellaneous > September 2005 > FAQ 4.48 How do I shuffle an array randomly?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author FAQ 4.48 How do I shuffle an array randomly?
PerlFAQ Server

2005-09-24, 3:56 am

This message is one of several periodic postings to comp.lang.perl.misc
intended to make it easier for perl programmers to find answers to
common questions. The core of this message represents an excerpt
from the documentation provided with Perl.

--------------------------------------------------------------------

4.48: How do I shuffle an array randomly?

If you either have Perl 5.8.0 or later installed, or if you have
Scalar-List-Utils 1.03 or later installed, you can say:

use List::Util 'shuffle';

@shuffled = shuffle(@list);

If not, you can use a Fisher-Yates shuffle.

sub fisher_yates_shuffle {
my $deck = shift; # $deck is a reference to an array
my $i = @$deck;
while (--$i) {
my $j = int rand ($i+1);
@$deck[$i,$j] = @$deck[$j,$i];
}
}

# shuffle my mpeg collection
#
my @mpeg = <audio/*/*.mp3>;
fisher_yates_shuffle( \@mpeg ); # randomize @mpeg in place
print @mpeg;

Note that the above implementation shuffles an array in place, unlike
the List::Util::shuffle() which takes a list and returns a new shuffled
list.

You've probably seen shuffling algorithms that work using splice,
randomly picking another element to swap the current element with

srand;
@new = ();
@old = 1 .. 10; # just a demo
while (@old) {
push(@new, splice(@old, rand @old, 1));
}

This is bad because splice is already O(N), and since you do it N times,
you just invented a quadratic algorithm; that is, O(N**2). This does not
scale, although Perl is so efficient that you probably won't notice this
until you have rather largish arrays.



--------------------------------------------------------------------

Documents such as this have been called "Answers to Frequently
Asked Questions" or FAQ for short. They represent an important
part of the Usenet tradition. They serve to reduce the volume of
redundant traffic on a news group by providing quality answers to
questions that keep coming up.

If you are some how irritated by seeing these postings you are free
to ignore them or add the sender to your killfile. If you find
errors or other problems with these postings please send corrections
or comments to the posting email address or to the maintainers as
directed in the perlfaq manual page.

Note that the FAQ text posted by this server may have been modified
from that distributed in the stable Perl release. It may have been
edited to reflect the additions, changes and corrections provided
by respondents, reviewers, and critics to previous postings of
these FAQ. Complete text of these FAQ are available on request.

The perlfaq manual page contains the following copyright notice.

AUTHOR AND COPYRIGHT

Copyright (c) 1997-2002 Tom Christiansen and Nathan
Torkington, and other contributors as noted. All rights
reserved.

This posting is provided in the hope that it will be useful but
does not represent a commitment or contract of any kind on the part
of the contributers, authors or their agents.
William James

2005-09-24, 9:56 pm

PerlFAQ Server wrote:
>
> If not, you can use a Fisher-Yates shuffle.
>
> sub fisher_yates_shuffle {
> my $deck = shift; # $deck is a reference to an array
> my $i = @$deck;
> while (--$i) {
> my $j = int rand ($i+1);
> @$deck[$i,$j] = @$deck[$j,$i];
> }
> }
>
> # shuffle my mpeg collection
> #
> my @mpeg = <audio/*/*.mp3>;
> fisher_yates_shuffle( \@mpeg ); # randomize @mpeg in place
> print @mpeg;


Perhaps you would be happier using Ruby:

puts %w(truth imprisons troll tellers gunnar).sort_by{ rand } * " "


troll gunnar imprisons truth tellers

Donald King

2005-09-25, 9:56 pm

William James wrote:
> PerlFAQ Server wrote:
>
>
>
> Perhaps you would be happier using Ruby:
>
> puts %w(truth imprisons troll tellers gunnar).sort_by{ rand } * " "
>
>
> troll gunnar imprisons truth tellers
>


You can do the equivalent of your suggestion in Perl as well:

# Equivalent to .sort { rand(3) - 1 }

print join(" ",
sort { 1 - int rand 3 }
qw(ruby trolls are quite silly)
), "\n";

# Equivalent to .sort_by { rand }
# Not as elegant because Perl doesn't clone .sort_by (yet)
# Of course, Perl has shortcuts that Ruby doesn't have, too...

print join(" ",
map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { [$_,rand] }
qw(ruby trolls are quite silly)
), "\n";

However, neither of these examples (including the Ruby one) shuffle an
array *in place*, which is what the example code did, and is necessary
to reduce memory requirements for large arrays. Your Ruby code, at
minimum, doubles the memory requirements of the array being sorted.

Also, since your Ruby code uses sorting -- an O(n log n) operation if
Ruby's algorithm was chosen wisely, which it probably was -- it will
take more and more time than necessary as the length of the array grows.
However, the Fisher-Yates shuffle used in the above code is O(n) and
will merely double in runtime when the array doubles in length.

--
Donald King, a.k.a. Chronos Tachyon
http://chronos-tachyon.net/
A. Sinan Unur

2005-09-26, 8:01 am

Donald King <dlking@cpan.org> wrote in news:CgJZe.78026$Sj1.70599
@okepread04:

> William James wrote:

....
[color=darkred]
> However, the Fisher-Yates shuffle used in the above code is O(n) and
> will merely double in runtime when the array doubles in length.


This probably does not matter when generating different starting locations
for a game, but it is important to note:

http://search.cpan.org/~abigail/Shu...uffle.pm#CAVEAT

Sinan

--
A. Sinan Unur <1usa@llenroc.ude.invalid>
(reverse each component and remove .invalid for email address)

comp.lang.perl.misc guidelines on the WWW:
http://mail.augustmail.com/~tadmc/c...guidelines.html
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com