Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Re: random elements from array - new twist

by rob_au (Abbot)
on Nov 05, 2002 at 07:01 UTC ( #210401=note: print w/replies, xml ) Need Help??

in reply to random elements from array - new twist

The solution provided by BrowserUK above is right on the money and is particularly good if the preservation of the original array set is important. If however this is not important and larger array sets are being manipulated, the following example using splice should prove to be more efficient.

sub pick (\@) { my $array = shift; return splice @{$array}, rand @{$array}, 1; } my @array = (1..15); my @results = (); push @results, pick @array for 1..5;

This code differs from the other solution above in that it makes use of the splice function to remove and return an element from the array, thereby ensuring that when the pick function is called again, that same value cannot be returned.


perl -e 'print+unpack("N",pack("B32","00000000000000000000000111011001")),"\n"'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://210401]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2020-10-31 22:19 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (291 votes). Check out past polls.