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

Re: random number with range

by borisz (Canon)
on Jun 01, 2006 at 17:35 UTC ( #553099=note: print w/replies, xml ) Need Help??

in reply to random number with range

Here is one way:
use List::Util 'shuffle'; my @nums = shuffle( 50 .. 200 );

Replies are listed 'Best First'.
Re^2: random number with range
by davido (Archbishop) on Jun 01, 2006 at 20:38 UTC

    Yes, that works. And that method is great if you want to grab multiple random numbers such that you never get the same one twice. For example, implementing a shuffled deck of cards, or drawing names out of a hat. But if all the OP wants is a single random number, or lots of random numbers uninhibited by such rules as "the number can never repeat", that solution is probably not the best way to do it.

    With a shuffled list you have the following problems:

    • Each number can only exist once, or at least a predetermined finite number of times. True random numbers are not dependant on what has already been picked. If you want only four aces to exist in a deck, your solution is great. If you want each subsequent draw to be from a 'fresh' deck, your method would require a new deck, and a new shuffle after each draw.
    • The actions of building the deck (the list), shuffling it, and copying it to @num each take O(n) time.
    • For any range of randoms, your 'deck' grows in memory requirements in a 1:1 relationship ( O(n) ). Thus, a huge range will require huge amounts of memory.

    On the other hand, simply picking a random number using rand insures that each subsequent random number isn't dependant on the previously selected numbers, no lists are built and maintained, and thus, time and memory requirements are only O(1).


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://553099]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2018-05-22 01:10 GMT
Find Nodes?
    Voting Booth?