Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: randomly choosing elements from an array

by jdporter (Paladin)
on Mar 19, 2003 at 06:44 UTC ( [id://244268]=note: print w/replies, xml ) Need Help??


in reply to randomly choosing elements from an array

The canonical way to choose one element randomly from an array @a is
$item = $a[ rand @a ];
If you need to do this n times, you could therefore do this:
my @items; for ( 1 .. $n ) { push @items, $a[ rand @a ]; }
However, you have not said whether you can validly choose the same value twice. If not, then you'll have to remove each element from the set when you choose it. Like so:
my @items; for ( 1 .. $n ) { push @items, splice @a, rand @a, 1; }
Of course, if you'd prefer not to destroy @a, then work on a disposable copy of it.

jdporter
The 6th Rule of Perl Club is -- There is no Rule #6.

Replies are listed 'Best First'.
Re: Re: randomly choosing elements from an array
by grantm (Parson) on Mar 19, 2003 at 09:01 UTC

    I recently had to solve the 'randomly select n unique elements from an array' problem. The solution I hit upon was to shuffle the list and take the first n elements. The trick being, you don't have to shuffle the whole list, you just need to ensure the first n elements were shuffled:

    my @list = 'a'..'z'; # use your data in +stead of this my $n = 5; # how many do you +need? foreach my $i (0..$n-1) { my $j = rand @list; ($list[$i], $list[$j]) = ($list[$j], $list[$i]); # swap ith and jth + elements }; print join(', ', @list[0..$n-1]), "\n";

    As you say though, the original poster didn't specify whether unique selections were a requirement.

Re: Re: randomly choosing elements from an array
by sulfericacid (Deacon) on Mar 19, 2003 at 16:09 UTC
    Wow, this seems to be a lot easier than the method everyone else is aiming at. For the script I will actually require to only randomly call back unique instances of the phrase.

    Thanks so much for your help!

    "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

    sulfericacid

Re^2: randomly choosing elements from an array
by msh210 (Monk) on Sep 02, 2015 at 21:25 UTC
    This would seem to disallow duplicate choices:
    my @items; while (1) { my $item = $a[ rand @a ]; push @items, $item unless $item ~~ @items; last if $n <= @items; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-24 21:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found