Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: random elements from array - new twist

by rob_au (Abbot)
on Nov 05, 2002 at 07:01 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2024-03-19 09:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found