Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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

by davido (Archbishop)
on Dec 07, 2012 at 06:18 UTC ( #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


Comment on Re: Idiom to return 0 or random number of array elements
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2014-08-31 04:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (294 votes), past polls