in reply to Select value from array w/o replacement (or destroying the array)
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.
|
|---|