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

Re: picking multiple random elements out of an array

by Masem (Monsignor)
on Feb 03, 2002 at 21:27 UTC ( [id://143147]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


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 - mneylon-pm@masemware.com || "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 Bishma (Beadle) on Feb 03, 2002 at 22: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.
Re: Re: picking multiple random elements out of an array
by dws (Chancellor) on Feb 03, 2002 at 23: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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://143147]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.