Re: Random number generator without duplicates?
Re: Random number generator without duplicates?
- Subject: Re: Random number generator without duplicates?
- From: email@hidden
- Date: Tue, 17 Apr 2001 14:59:31 -0700
--How can I get a list of random numbers that does not include any
duplicates?
--I would want to use these parameters: six random numbers from 1 to 56, as
a
--list or as six variables, no duplicate numbers.
Here's a slightly different approach than what others have offered.
Rather than check to see if each selected item is in the new list this
method treats the original list as if it were a deck of cards and chooses
one item at random from the deck and removes it from the deck.
>
>>>The buzzword for searching is "shuffling".
Funny, the snippet below came from a handler called Shuffel...
>
>>>There was an article in Dr. Dobbs Journal about a year ago. You start
with an indexed array of integers from 1 to N and move them around at
random. It makes a difference whether or not you allow an individual
element - a card - to be moved twice. I have a MacPerl script which I have
been meaning to update to the Dr. Dobbs recommendations but it works now.
if you'd like it - ask.
>
>>I notice after a few trials that the random number function is
generating duplicates after only a few iterations.
Each call to generate of the Random number command is a new call and is
not effected at all by what was just generated.
>
>>* 39% (22) of the values were never generated
>
>>* 28% of the values were generated once
>
>>* 1 of the values was generated 4 times
Those numbers don't seem out of the ordinary to me. Think of it as if you
were dealing a cards by pulling a random card from a fresh deck each time.
Yes some cards will be duplicated some cards you will never see and some
you may see three, four or more times.
For that reason if you were dealing more cards (say bridge rather than
poker) I suspect this method could be faster than comparing to the list
because with comparing you'll have to remove a number of duplicates.
set newDeck to {}
repeat with x from 1 to 56
set the end of newDeck to x
end repeat
set newHand to {}
repeat 6 times
set lastCard to count of newDeck
set cardToPick to (random number from 1 to (count of newDeck))
set the end of newHand to item cardToPick of newDeck
set newDeck to (items 1 thru (cardToPick - 1) of newDeck) & the rest
of (items (cardToPick) thru (count of newDeck) of newDeck)
end repeat
return newHand
hth,
ES