# 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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.