For a multiplayer game I need to produce the same sequence of random numbers on all participating devices. Obviously, this is achieved by using the same seed on all devices. Problems arise when random()
is called outside of the routine that is supposed to produce the same sequence on all devices. In this routine, I therefore try to use setstate
to preserve the state array. As far as I understood man random(3)
, calls to random()
outside of this routine then should not change the sequence.
However, the following code does not produce the same output for Run 1 and 2:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[])
{
char state[256];
printf("Run 1 : ");
initstate(123, state, 256);
for (int i=1; i < 10; i++) {
printf("%ld ", random());
}
printf("\nRun 2 : ");
initstate(123, state, 256);
for (int i=1; i < 10; i++) {
setstate(state); // load preserved state
printf("%ld ", random());
*state = *setstate(state); // preserve state
random(); // this simulates a call to random() from outside
}
printf("\n");
return 0;
}
Run 1 : 1597493280 1407130876 1753502901 1965067074 377602131 83146350 274392949 1718024305 1016176754
Run 2 : 1597493280 537479855 1611694138 941096776 83164437 1459338036 1256894804 1618690717 1091902527
Program ended with exit code: 0
Does anyone have any idea why? Or maybe there is another way to achieve the desired result?
For the record: Running on OS X and iOS using Xcode 5.
EDIT With the help of Arkku and minitech, the following change makes Run 2's output identical to Run 1:
printf("\nRun 2 : ");
char otherstate[256];
initstate(123, state, 256);
for (int i=1; i < 10; i++) {
// preserve whatever state is currently active
// and set the current state to "my" state
memcpy(otherstate, setstate(state), 256);
printf("%ld ", random());
// switch back to the other state
memcpy(state, setstate(otherstate), 256);
// now this call does not affect the sequence that get's printf'd
random();
}
printf("\n");