develooper Front page | perl.beginners | Postings from April 2002

Re: Scripts picks random elements from array , but it repeats sometim es

From:
Felix Geerinckx
Date:
April 29, 2002 13:33
Subject:
Re: Scripts picks random elements from array , but it repeats sometim es
Message ID:
Xns91FFE582573Cfge123@209.85.157.220
on Mon, 29 Apr 2002 18:55:41 GMT, Jim-Cont Flaherty wrote:

> Hello , My script picks out random elements from an array , but it
> sometimes repeats ( which is no good) .. I want to prevent this , Do
> I delete the element from the array .... or is there a better way ?

Lookup the 'fisher_yates_shuffle' with 

    	perldoc -q shuffle

    	How do I shuffle an array randomly?

If you don't want to mess with your original @array, you can create a 
second array @iarray = (0..$#array), and shuffle that:

    my @dwarfs = qw (Doc Happy Bashful Sneezy Sleepy Grumpy Dopey); 
    my @idwarfs = (0..$#dwarfs);
    fisher_yates_shuffle( \@idwarfs );   
    for (@idwarfs) {
        print "$dwarfs[$_]\n";
    }

-- 
felix



nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About