I recently had to solve the 'randomly select n unique elements from an array' problem. The solution I hit upon was to shuffle the list and take the first n elements. The trick being, you don't have to shuffle the whole list, you just need to ensure the first n elements were shuffled:
my @list = 'a'..'z'; # use your data in +stead of this my $n = 5; # how many do you +need? foreach my $i (0..$n-1) { my $j = rand @list; ($list[$i], $list[$j]) = ($list[$j], $list[$i]); # swap ith and jth + elements }; print join(', ', @list[0..$n-1]), "\n";
As you say though, the original poster didn't specify whether unique selections were a requirement.
In reply to Re: Re: randomly choosing elements from an array
by grantm
in thread randomly choosing elements from an array
by sulfericacid
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |