in reply to Picking unique element in random from a array

rsriram,

Here is a way to do it.

use strict; use warnings; use Data::Random qw(:all); my @array = (1, 2, 1..120); #assign values to array my @ten = rand_set( set => \@array, size => 10 );#get random print "Ten unique random numbers: @ten";

updated: Added random module. Removed identifying unique elements as per L~R's advice. As far as runtime is concerned, it is not most efficient way though. Take a look at Limbic~Region node or davorg's. Limbic~Region Thanks.

Prasad

Replies are listed 'Best First'.
Re^2: Picking unique element in random from a array
by Limbic~Region (Chancellor) on Aug 09, 2006 at 12:47 UTC
    prasadbabu,
    I think you have misunderstood though it is not your fault and I might be the one that is wrong. rsriram said unique elements but meant unique indices judging by the rest of the node. In other words, by repeating the random number selection, the same index was appearing multiple times. While your updated use of the Data::Random module gets the job done, the %unique is not needed. Update: Your second update corrects all the problems and this is a valid solution.

    Several ways to do this that involve changing the original array are to use List::Util's shuffle() as davorg has suggested or use splice to pull out elements randomly. Alternatively, a parrallel array of indices allows the original array to remain intact.

    my (@index, @rand); @index = 0 .. $#array; push @rand, splice(@index, rand @index, 1) for 1 .. 10; print "@array[@rand]\n"; # untested

    Update: I added a couple of alternatives that do not leave the original array intact. Additionally, I need to point out that your use of Data::Random can be terribly runtime inefficient. See my update in this node for details. The alternatives consume more memory (trading space for time). I also originally incorrectly thought that the module was returning the set in the original order by default but it isn't.

    Cheers - L~R