in reply to Select value from array w/o replacement (or destroying the array)

Here is a one-at-a-time Fisher-Yates shuffle but using an array of indices instead of modifying your array of numbers directly (if even avoids having to move around half of the extra array via splitsplice):

#!/usr/bin/perl -lw use strict; my @inviolable= getNumbers(); my $pickNext= genPickWNoReplace( \@inviolable ); while( 1 ) { print $pickNext->(); } sub genPickWNoReplace { my( $av )= @_; my @idx= 0..$#$av; return sub { die "No more items left to pick from" if ! @idx; my $o= int rand @idx; my $pick= $av->[ $idx[$o] ]; $idx[$o]= $idx[-1]; pop @idx; return $pick; }; }

(update above thanks to fenLisesi's correction)

- tye        

  • Comment on Re: Select value from array w/o replacement (or destroying the array) (indirect shuffle)
  • Download Code