Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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


In reply to Re: Idiom to return 0 or random number of array elements by davido
in thread Idiom to return 0 or random number of array elements by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-19 18:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found