a random sub-array
am 11.09.2007 18:27:11 von 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
Re: a random sub-array
am 11.09.2007 18:42:20 von Paul Lalli
On Sep 11, 12:27 pm, Jie wrote:
> 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
Re: a random sub-array
am 11.09.2007 19:36:08 von Jie
Hi, Paul:
Thank you very much!
This Shuffle works great!
jie
On Sep 11, 12:42 pm, Paul Lalli wrote:
> On Sep 11, 12:27 pm, Jie wrote:
>
> > 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