Monks, I am currently pondering this conundrum. I have an array of numbers (not shown below), and I need to randomly select a value from that array (n) number of times, without replacement.

I know this is possible with a splice  ($ranpop = splice(@holder, int rand(@holder), 1)); but I do not want to destroy the array.

I was thinking something along these lines:

use strict; use warnings; my @final; my $item; my @list = (2, 1, 4, 3, 8, 5); #already selected from array #image another loop someplace else that is pushing into @list for (1 .. 5) { #getting 5 numbers not on the list above... my $find = int rand (10); #my "array" I am picking from is 0-10 #below this is my attempt to solve my problem my $found_flag = 0; foreach my $item ( @list ) { if( $item eq $find ) { $found_flag = 1; last; } } if( $found_flag ) { print "Found $find.\n"; until ( $find != $item ) { $find = int rand (10); } } #I tried to basically say # if (the item is already in the array) { # pick a value until it is not found in the array # } push @final, $find; } print "@final \n";
But I am doing something wrong, and I can not figure it out. Somewhere or something in that last loop needs to be adjusted. Any help is appreciated.

-Bio

Even a blind squirrel finds a nut sometimes.

In reply to 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.