# The solutions presented so far by the other monks all return a # subset of a shuffle of the whole (except tye's) array of possible # numbers. Compare the following beautiful algorithm, which calls # rand() only as many times as there are numbers to pick. It is # attributed to Bob Floyd by Jon Bentley, in his "More Programming # Pearls" (Addison-Wesley, 1988). Here is Bentley's explanation, # which I've adapted for the displayed Perl code: # # "We can appreciate the correctness of [the algorithm] # anecdotally. When $m is 5 and $n is 10, the algorithm first [...] # computes in %sample a 4-element sample in the range 0..8. Next it # assigns to $val a random integer in the range 0..9. Of the 10 # values that $val can assume, exactly 5 result in inserting 9 into # %sample: the four values already in %sample, and the value 9 # itself. Thus element 9 is inserted into the set with the correct # probability of 5/10." use strict; sub sample { # Returns a list of $m different random integers # between 0 and $n - 1. my ($m, $n) = @_; my %sample; my $j = $n - $m + 1; while ($m-- > 0) { my $val = int($j * rand(1)); $sample{ exists $sample{$val} ? $j - 1 : $val } = 0; ++$j; } keys %sample; }
In reply to Re: Creating an array of unique numbers
by lucs
in thread Creating an array of unique numbers
by TStanley
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |