Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
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
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 pondering the Monastery: (7)
As of 2019-05-22 22:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you enjoy 3D movies?



    Results (140 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!