laziness, impatience, and hubris PerlMonks

### 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 );
Boris

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).

Dave

Create A New User
Node Status?
node history
Node Type: note [id://553099]
help
Chatterbox?
 [thepkd]: Hey 1nickt sorry man. What [GotToBTru]: a ref too far ;) [thepkd]: Yes this is my first time in cb. Trying to work my way around. [JohnCub]: "A ref too far" would make a good title for anyone's perl memoirs [thepkd]: Anyways it works with \$aohoaoh[0]->{'foo '}[0]->{'bar'} [GotToBTru]: "I did it my \$way" [JohnCub]: I hope \$way isn't a hashref. ;)

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (12)
As of 2016-12-06 13:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
On a regular basis, I'm most likely to spy upon:

Results (105 votes). Check out past polls.