in reply to randomly choosing elements from an array
If you need to do this n times, you could therefore do this:$item = $a[ rand @a ];
However, you have not said whether you can validly choose the same value twice. If not, then you'll have to remove each element from the set when you choose it. Like so:my @items; for ( 1 .. $n ) { push @items, $a[ rand @a ]; }
Of course, if you'd prefer not to destroy @a, then work on a disposable copy of it.my @items; for ( 1 .. $n ) { push @items, splice @a, rand @a, 1; }
jdporter
The 6th Rule of Perl Club is -- There is no Rule #6.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: randomly choosing elements from an array
by grantm (Parson) on Mar 19, 2003 at 09:01 UTC | |
by merlyn (Sage) on Mar 22, 2003 at 16:46 UTC | |
|
Re: Re: randomly choosing elements from an array
by sulfericacid (Deacon) on Mar 19, 2003 at 16:09 UTC | |
|
Re^2: randomly choosing elements from an array
by msh210 (Monk) on Sep 02, 2015 at 21:25 UTC |