Link to home
Start Free TrialLog in
Avatar of bazzle
bazzle

asked on

Generating unique random numbers

The following code will generate nine random numbers, but how can I change the code so that it will generate nine unique random numbers?

srand (time|$$);
$square=1;
while ($square != 10) {
$random=int(rand(50))+1;
$word{$square}=$random;
$square++
}
ASKER CERTIFIED SOLUTION
Avatar of icd
icd

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of icd
icd

OK. Here is an alternative that will always give a pseudo random number sequence, without repeats (upto a maximum of 50 numbers!).

$random = (time|$$);
$square=1;
while ($square != 10) {
$random = ($random * 213 + 11) % 50;
$word{$square}=$random;
$square++
}

The sequence will give you ten numbers, guaranteed to be different and showing pseudo random characteristics. Given the same seed value the generator will always generate the same sequence, but that  is true of any computed random number sequence.

Avatar of ozo
(time+$$) is more likely to give a unique seed than (time|$$)

 $random = ($random * 213 + 11) % 50;
Might as well be
 $random = ($random * 13 + 11) % 50;
And there's correlation in the way different batches of 10 overlap each other.
It's also weak in that there are only 50 distinct seeds.

One way to implement suggestion 1. could be:
 1 while( $previous{$random=int(rand(50))+1} )
 $previous{$random}=1;

But for large sequences, the approach from the FAQ may be better:
 srand;
 @new = ();
 @old = 1 .. 50;
 for( @old ){
   my $r = rand @new+1;
   push(@new,$new[$r]);
   $new[$r] = $_;
 }
#or
 @word=();
 @old = 1 .. 50;
 while( @word < 10 ){
  my $r = rand @old;
  push(@word,$old[$r]);
  $old[$r] = $old[-1];
  pop(@old);
 }
(since you're indexing %word with integers in sequence,
you might as well use an @word array instead of a hash)

Another problem with
 $random = ($random * 213 + 11) % 50;
is that with a seed of 22 (or 47) it generates only 2 unique values.
(there are also 8 seeds which generate only 4 unique values)