a random sub-array

J

Jie

I have an array like below:
@Big_array = (1, 2, 3, 4, 6, 7,10);

now I need to randomly generates a sub-array with 3 elements only,
say.

i tried to read the documentation for rand() but could not find the
solution. most of the examples online is talking about how to generate
ONE random element, but i need 3....

I guess it would something like below, but it does not work....
@new_array = rand(3, @Big_array)



Jie
 
P

Paul Lalli

I have an array like below:
@Big_array = (1, 2, 3, 4, 6, 7,10);

now I need to randomly generates a sub-array with 3 elements only,
say.

i tried to read the documentation for rand() but could not find the
solution. most of the examples online is talking about how to generate
ONE random element, but i need 3....

So just do it three times.
my @sub_array = map { $Big_array[rand @Big_array] } 1..3;

Of course, this gives the possibility that you could have repeated
elements in your sub array. If you don't want that, you'll have to do
a little more work.

First, make a copy of the array that you can destroy as we build the
sub array:
my @copy = @Big_array;
Then, randomly splice out an element as many times as you need to:
my @sub_array;
for (1..3) {
push @sub_array, splice @copy, rand(@copy), 1;
}

Alternatively, use List::Util's shuffle() function to shuffle the
original, then just take the first three elements.
use List::Util qw/shuffle/;
my @sub_array = (shuffle @Big_array)[0,1,2];

Paul Lalli
 
J

Jie

Hi, Paul:

Thank you very much!

This Shuffle works great!

jie

I have an array like below:
@Big_array = (1, 2, 3, 4, 6, 7,10);
now I need to randomly generates a sub-array with 3 elements only,
say.
i tried to read the documentation for rand() but could not find the
solution. most of the examples online is talking about how to generate
ONE random element, but i need 3....

So just do it three times.
my @sub_array = map { $Big_array[rand @Big_array] } 1..3;

Of course, this gives the possibility that you could have repeated
elements in your sub array. If you don't want that, you'll have to do
a little more work.

First, make a copy of the array that you can destroy as we build the
sub array:
my @copy = @Big_array;
Then, randomly splice out an element as many times as you need to:
my @sub_array;
for (1..3) {
push @sub_array, splice @copy, rand(@copy), 1;

}

Alternatively, use List::Util's shuffle() function to shuffle the
original, then just take the first three elements.
use List::Util qw/shuffle/;
my @sub_array = (shuffle @Big_array)[0,1,2];

Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,216
Latest member
topweb3twitterchannels

Latest Threads

Top