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

Re: Grep (WAS RE: searching an array)

Thread Previous
From:
Jenda Krynicky
Date:
March 30, 2002 13:44
Subject:
Re: Grep (WAS RE: searching an array)
Message ID:
3CA63FAA.30094.1BF4259@localhost
From:           	"John W. Krahn" <krahnj@acm.org>
> Jenda Krynicky wrote:
> > And if you want 6 unique :
> > 
> >     my @myarr;
> >     {       # this block is here just to restrict the availability
> >             # of %seen
> >         my %seen;
> >         while (@myarr < 6) {
> >             my $num = 1 + int(rand 35);
> >             push @myarr, $num
> >                 unless $seen{$num}++
> >         }
> >     }
> > 
> > if you wanted that a bit longer:
> > 
> >     my @myarr;
> >     {       # this block is here just to restrict the availability
> >             # of %seen
> >         my %seen;
> >         while (@myarr < 6) {
> >             my $num = 1 + int(rand 35);
> >             if (! $seen{$num}) {
> >                 push @myarr, $num;
> >                 $seen{$num} = 1
> >             }
> >         }
> >     }
> 
> Because of the nature of "randomness" this algorithm could take a long
> time to run.  

It takes a random amout of time ;-)

> Better to shuffle an array of 35 numbers and pick six.

I always feel uneasy about shuffling. I never know whether I shuffled 
sufficiently :-)

Jenda

=========== Jenda@Krynicky.cz == http://Jenda.Krynicky.cz ==========
There is a reason for living. There must be. I've seen it somewhere.
It's just that in the mess on my table ... and in my brain
I can't find it.
					--- me

Thread Previous


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