Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: picking multiple random elements out of an array

by Masem (Monsignor)
on Feb 04, 2002 at 02:27 UTC ( #143147=note: print w/replies, xml ) Need Help??

in reply to picking multiple random elements out of an array

There's several different ways I can think of:
  • Use Algorithm::Shuffle to randomly shuffle the list, then grab the first 5 items from it. If you are removing items from the list, and don't care about order, and doing this often, this might be the best way, but will be slow with a very large array.
  • Generate a random number from 0 to the size of your array. Splice out that item from the array. Repeat 4 more times.
  • Variation of either of the above if you want to keep your array intact is to use a new array , (0..scalar @array-1) as the array to modify; once you have your items from here, treat these as indices to your main array.

Dr. Michael K. Neylon - || "You've left the lens cap of your mind on again, Pinky" - The Brain
"I can see my house from here!"
It's not what you know, but knowing how to find it if you don't know that's important

Replies are listed 'Best First'.
Re: Re: picking multiple random elements out of an array
by dws (Chancellor) on Feb 04, 2002 at 04:09 UTC
    Here's a "variation of the above" code fragment from an ancient script. It produces a set of numbers which can be used as indices in an array slice.
    # @indices = randomsubset(scalar @array, $size_of_subset); sub randomsubset { my @indices = 0 .. $_[0] - 1; my @subset = (); push @subset, splice(@d, int rand @indices, 1) for 1 .. @_[1]; @subset; } print join (" ", randomsubset(50,5)), "\n";
    (The overly specific name indicates sloppy thinking on my part, for which I plead guilty.)

    IIRC, there's something equivalent in the Cookbook.

Re: Re: picking multiple random elements out of an array
by Bishma (Beadle) on Feb 04, 2002 at 03:47 UTC
    The shuffle will work well, I never thought of that. The other was what I was trying to avoid because I didn't want to have to check for duplicates.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://143147]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2018-04-26 15:31 GMT
Find Nodes?
    Voting Booth?