Re: Best way to get a non-repeating random number?
Re: Best way to get a non-repeating random number?
- Subject: Re: Best way to get a non-repeating random number?
- From: Michael Ash <email@hidden>
- Date: Wed, 15 Apr 2009 12:46:01 -0400
On Wed, Apr 15, 2009 at 12:34 PM, Peter Castine <email@hidden> wrote:
> On 14-Apr-2009, at 22:32, Eric E. Dolecki wrote:
>>
>> int result = (arc4random()%9) + 1;
>>
>> if (result >= activeTarget) ++result;
>>
>> activeTarget = result;
>>
>> That seems a little odd to me to do things that way - but I'm not really
>> sure.
>
> This will give you biased results. Instead of equally distributed values in
> {1, 2,.. 10}, you will only get 10 just over 1.2% of the time and 1 a bit
> under the expected 10%, with the other values taking up the slack.
> Additionally, the absolute differences of consecutive values will not be
> equally distributed. There will be a skew towards sequences where x(n+1) =
> x(n) + 1. The second point may or may not be a problem for a game whereas
> the first point is probably too deadly even for a game.
No it won't. The first line generates numbers in the range [1,9],
evenly distributed (ignoring the very small modulo bias). The second
line shifts the end of the range so that the number now falls into
either [1,activeTarget) or (activeTarget, 10]. It is still evenly
distributed in those two ranges.
> The following would deal with the first point:
>
> int result = myRandomNumberGenerator() % 10 + 1;
> if (result == activeTarget)
> result = result % 10 + 1;
> activeTarget = result;
This one has a massive flaw in that it will produce
(activeTarget+1) 20% of the time and produce the other numbers only
10% of the time.
Do we really need One Thousand Ways To Be Wrong About Random Numbers?
The OP described a perfectly good technique for this in his *original
post to this thread*.
Mike
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden