2009/11/3 John W. Krahn <jwkr...@shaw.ca>:
> Majian wrote:
>> my @array = ('uriel', 'daniel', 'joel', 'samuel');
>>
>> Now what I want is create a process so every time I print the array it
>> prints  one element from the array .
>>
>> I wrote it like this :
>>
>> #!/usr/bin/perl -w
>>
>> use strict;
>
> use List::Util 'shuffle';
>
>
>> my @array = ('uriel', 'daniel', 'joel', 'samuel');
>> print "Array before random: @array\n\n";
>>
>> print "Array of random: $array[rand @array]\n";
>
> @array = shuffle @array;
>
> print "Array of random: @array\n\n";

That doesn't pick one random element from the array. That shuffles the
whole array.

I feel it's probably worth saying here that shuffling an array is an
easy thing to get wrong -- ie if you try to roll your own subroutine
its easy to accidentally make some permutations more likely than
others. One example of how it can look right but not be right:

sub badshuffle {
    my @array = @_
    for my $i (0..$#array) {
        # For each element, randomly swap it with another element
        my $rand = rand @array;
        ($array[$i], $array[$rand]) = ($array[$rand], $array[$i]);
    }
}
This routine is not balanced. Some outcomes are more common than
others, though I leave proof as an exercise to the reader.

If you are interested in learning about doing shuffling yourself from
an academic point of view, see:
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
and pay particular attention to:
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Implementation_errors

But if you just want to get it done or are writing production code,
use List::Util::shuffle as John W Krahn says above. Don't roll your
own in production code.

Philip

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to