http://qs1969.pair.com?node_id=1007692


in reply to Idiom to return 0 or random number of array elements

LanX got to the @slice[ 0 .. -1 ] solution ahead of me, but I'm thinking you might still be missing something.

In your first example, "$element = $array[int rand @array];", you're selecting a random element. In your second example, "@elements = @array[0 .. int rand @array];" you're selecting a random number of elements, but the elements being selected are not random except for the quantity. If your array contains "a, b, c, d, e", you'll get "a", or "a,b", or "a,b,c", etc. Even after dealing with the ability to get no elements at all, you're still not actually getting random elements.

Maybe that's what you want. Or maybe you want a random number of random elements (with no duplicates). If that's the case, you might just shuffle:

use List::Util 'shuffle'; use List::MoreUtils 'minmax'; my @array = 'a' .. 'z'; my @quantities; for( 1 .. 100 ) { # --------------------This is the solution line: ------------------- +---------- my @selected = @{ [ shuffle @array ] }[ 0 .. int( rand @array + 1 ) +- 1 ]; # ------------------------------------------------------------------ +------ push @quantities, my $quantity = @selected; print "@selected => ($quantity)\n"; } print "\nMin/Max elements: (", join( ',', minmax @quantities ), ")\n";

Dave