Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Idiom to return 0 or random number of array elements

by davido (Cardinal)
on Dec 07, 2012 at 06:18 UTC ( [id://1007692]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2024-03-28 23:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found