(U) RE: (repost) how can i generate 10 unique (non repeating) num bers
From: Michael Johnson (Michael.Johnson_at_oln-afmc.af.mil)
Date: 07/26/04
- Next message: u235sentinel_at_comcast.net: "Re: Serious question on using Perl or not..."
- Previous message: Eric Walker: "Re: Having trouble using the Shell within Perl script."
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
To: 'Flemming Greve Skovengaard' <dsl58893@vip.cybercity.dk>, beginners@perl.org Date: Mon, 26 Jul 2004 14:14:59 -0700
CLASSIFICATION: UNCLASSIFIED
just add a little more logic to determine if the new number has already been
selected. This will require storing to a list and then checking that list
each time a new number is generated.
-----Original Message-----
From: Flemming Greve Skovengaard [mailto:dsl58893@vip.cybercity.dk]
Sent: Thursday, July 22, 2004 4:37 AM
To: beginners@perl.org
Cc: Absolut Newbie
Subject: Re: (repost) how can i generate 10 unique (non repeating)
numbers
Absolut Newbie wrote:
> Hi,
>
> (reposting this since i did not see the original in my newsreader or
google)
>
> I want to generate 10 numbers from 1..15 and put them in an array.
>
> easy ?
> while ($fill < 10){
> $foo = int(rand(15));
> unshift(@array, $foo);
> $fill++;
> }
> print "the \@array is --> @array\n";
>
> my problem is that many times the numbers repeat themselves in the array.
>
> the @array is --> 5 10 8 3 0 13 14 9 0 10
>
> how can i generate 10 unique (non repeating) numbers from a range to put
in
> the array ?
>
> thanx.
>
>
>
> ---
>
> Checked by AVG anti-virus system (http://www.grisoft.com).
> Version: 6.0.719 / Virus Database: 475 - Release Date: 7/18/2004
>
>
Be patient when posting.
This will generate numbers between 1 and 15.
foreach (1..10) {
my $bar = int(rand(15)) + 1; # Since you want numbers 1..15 not 0..14
unshift(@array, $bar);
}
Since rand uses the internal clock (correct me if I am wrong) you're bound
to get repeated numbers. If you only want non-repeating numbers, run through
the array and only unshift if the number is not in the array already.
-- Flemming Greve Skovengaard The prophecy of the holy Norns a.k.a Greven, TuxPower a tale of death and doom <dsl58893@vip.cybercity.dk> Odin saw the final sign 4112.38 BogoMIPS the end is coming soon -- To unsubscribe, e-mail: beginners-unsubscribe@perl.org For additional commands, e-mail: beginners-help@perl.org <http://learn.perl.org/> <http://learn.perl.org/first-response> Classification: UNCLASSIFIED
- Next message: u235sentinel_at_comcast.net: "Re: Serious question on using Perl or not..."
- Previous message: Eric Walker: "Re: Having trouble using the Shell within Perl script."
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|