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

Re: random index in array - no duplicates

by crazyinsomniac (Prior)
on Jun 07, 2002 at 00:38 UTC ( #172401=note: print w/replies, xml ) Need Help??


in reply to random index in array - no duplicates

An option is to use splice. It's probably not the most efficient (you can always benchmark to make sure), but otherwise you can't get away with a single pass (at least not using rand, there probably is a perl module to only spit out unique random values, but its destined to be less efficient than just keeping track yourself).

 
______crazyinsomniac_____________________________
Of all the things I've lost, I miss my mind the most.
perl -e "$q=$_;map({chr unpack qq;H*;,$_}split(q;;,q*H*));print;$q/$q;"

  • Comment on Re: random index in array - no duplicates

Replies are listed 'Best First'.
Re: random index in array - no duplicates
by Abigail-II (Bishop) on Jun 07, 2002 at 11:28 UTC
    A splice isn't efficient. It's essentially quadratic in the size of the array, while a shuffle is linear.

    Or to be more precise. If you have an array of size N and you want to draw M elements from it (without duplicates), splice will take time proportional to N * M, while the suffle will take time proportional to N + M (or just M if you get a reference to the array).

    Abigail

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (2)
As of 2022-12-04 22:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?