Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
954 views
in Technique[技术] by (71.8m points)

ios - generate reliable pseudorandom number

I want to write a multiplayer game on iOS platform. The game relied on random numbers that generated dynamically in order to decide what happen next. But it is a multiplayer game so this "random number" should be the same for all device for every player in order to have a consistent game play.

Therefor I need a good reliable pseudorandom number generator that if I seed it a same number first than it will keep generate same sequences of random number on all device (iPad/iPhone/iPodTouch) and all OS version.

Looks like srand and rand will do the job for me but I am not sure does rand guarantee to generate same number on all device across all OS version? Otherwise is any good pseudorandom number generate algorithm?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the C standard (and Objective C is a thin layer on top of C so this should still hold):

If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated.

There's no guarantee that different implementations (or even different versions of the same implementation) will give a consistent sequence based on the seed. If you really want to guarantee that, you can code up your own linear congruential generator, such as the example one in the standard itself:

// RAND_MAX assumed to be 32767.
static unsigned long int next = 1;
void srand(unsigned int seed) { next = seed; }
int rand(void) {
    next = next * 1103515245 + 12345;
    return (unsigned int)(next/65536) % 32768;
}

And, despite the fact that there are better generators around, the simple linear congruential one is generally more than adequate, unless you're a statistician or cryptographer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...