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

RE: Scripts picks random elements from array , but it repeats sometimes

Thread Previous | Thread Next
From:
Wagner-David
Date:
April 29, 2002 12:19
Subject:
RE: Scripts picks random elements from array , but it repeats sometimes
Message ID:
113A7A0D1F47D511B92E00D0B7E03DAB0187BDC0@pmail02.vikingfreight.com
	Here is one option:
#!perl -w
my @numbers = qw( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 );
my $numofques = scalar(@numbers);
my @MySeen = ();

while($numofques > 0) {
    $index   = rand @numbers;
    next if ( defined$MySeen[$index] );
    $element = $numbers[$index];
    printf "%-3d ", $element;
    $MySeen[$index] = 1;
    $numofques--;
 }
printf "\n";

Output:
12  16  5   19  15  14  8   17  7   18  1   13  3   10  6   9   2   11  4

Wags ;)

-----Original Message-----
From: FLAHERTY, JIM-CONT [mailto:Jim.Flaherty@cnet.navy.mil]
Sent: Monday, April 29, 2002 11:58
To: Beginners (E-mail)
Subject: FW: Scripts picks random elements from array , but it repeats
som etimes


 
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 ? And how do I do
either ?  
 
 
 
my mistake here is the code 
 
 
 
 
while($numofques > 0) {
    $index   = rand @numbers;
    $element = $numbers[$index];
 
 
 

 
 
 
 
 
Thanks 
Jim

Thread Previous | Thread Next


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