On Apr 14, 2009, at 1:32 PM, Eric E. Dolecki wrote:

My apologies - what  I meant to type was that I AM doing this:

int tmp = (arc4random()%10)+1;

while (tmp == activeTarget) {

 tmp = (arc4random()%10)+1;

}

activeTarget = tmp;


This is for a game, so it's not very critical or anything. Someone told me that I might want to avoid a while loop at all by doing something like this:


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.

For a game, you almost certainly don't care about the quality of your random numbers. You don't need perfect statistical behavior (like a physical simulation) or cryptographic un-guessability (like security software). All you need is "looks random enough" and "fast".

In that case, arc4random() is overkill. That's a cryptographic random number generator, so it's slow. random() would be faster and still random enough. Just remember to call srandomdev() once at the start of your program, or else you might get the same sequence of random numbers every time you run.

The increment solution is a clever one that doesn't return the same number twice in a row, but otherwise avoids unfairly returning some numbers more often than others. (Try it - write a test program that generates a few million numbers and counts the results.) It should be as good as the try-again algorithm for your purposes, and faster.


--
Greg Parker     gpar...@apple.com     Runtime Wrangler


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to