In my experience, the circumstances for random number selection are relevent to the process. Many selection algorithms are costly in terms of time or computing power or are unnecessarily complex for the task at hand. Selecting 10 random numbers may not require the same complexity as selecting 10,000. Here are two possibilities I've used before.
#!/usr/perl use warnings; use strict; my @tmpary = (); my @num = (); my $ulmt = 10; my $nrneeded = 3; srand; # if the order of selection of random number is not important my $idx = 0; my $cntr = 0; # this does waste the 1st element but simplifies indexing # and does cost the memory but for small lists this isn't # significant push @tmpary, undef for (0..$ulmt); while($cntr < $nrneeded){ $idx = int(rand($ulmt-1)+1); # map range into (1..ulmt) unless($tmpary[$idx]){ $cntr++; $tmpary[$idx] = 1; } } $tmpary[$_] && push @num, $_ for (0..$ulmt); print "$_, " foreach (@num); print "\n"; # if order of selection of random numbers is important my %idx = (); my $val = 0; @num = (); while(scalar keys %idx < $nrneeded){ $val = int(rand($ulmt-1)+1); # map range to (1..ulmt) $idx{$val} ||= 1 && push @num, $val; } print "$_, " foreach (@num); print "\n"; exit;

In reply to Re: Select three random numbers between 1..10 by periapt
in thread Select three random numbers between 1..10 by Perl_User

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.