Why not copy the array and destroy the copy? Is it big?

An easy solution would involve List::Util::shuffle. Just shuffle the (copied) array and pop n items off of it.

If you really can't copy the array, maybe this would work:

# 20 random integers, 0-99 my @orig_list = map { int rand 100 } 0 .. 20; my @selected = (); # items selected my $desired = 10; # how many items to select my %found = (); # indexes already used while ( scalar @selected < $desired ) { my $index; $index = int rand @orig_list until ! $found{$index}++; push @selected, $orig_list[$index]; }

Note that this is not very efficient when the number of items desired approaches the size of the original list. However, it avoids copying the whole list or modifying any part of it.


In reply to Re: Select value from array w/o replacement (or destroying the array) by kyle
in thread Select value from array w/o replacement (or destroying the array) by BioNrd

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.