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