XP is just a number PerlMonks

### Re^2: random number with range

by davido (Archbishop)
 on Jun 01, 2006 at 20:38 UTC ( #553145=note: print w/replies, xml ) Need Help??

in reply to Re: random number with range
in thread random number with range

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://553145]
help
Chatterbox?
 [choroba]: Aren't they the standard X colours? [ambrus]: choroba: that's not clear, since Tk runs on systems that don't even have X.

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2017-10-17 11:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My fridge is mostly full of:

Results (227 votes). Check out past polls.

Notices?