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