unix - C - How to ENSURE different random number generation in C when program is executed within the same second? -
for assignment, supposed ensure that, when execute program within same second, should return different numbers. however, i've read other posts , can't quite figure out how within same second. if run code:
int main() { srand(time(null)); for(count = 0; count < 10; count++) { printf("%d\n", rand()%20 + 1); } return 0; }
i end same result when executed within same second. know how mix results within same second? i'm operating in unix environment if makes difference. thanks.
to prevent 2 programs generating same pseudo-random numbers rand()
, must, @ minimum use different seeds srand()
.
the source seeds 2 runs of program derived either
1) same source - mechanism unique generation.
2) random source , chance of same seed generation tolerable low.
1a #1, time()
used, definition, programs start in same second, simplistic use of fails.
1b attempting create file both program access write "i started seed - 12345, if generate seed try again".
1c approach use finer time hinted (@will) - that's better finer resolution may not enough.
2a platforms provide random number via system function call, since depends on various esoteric system events , slow compared rand()
, useful seeding srand()
. not systems provide this.
[edit] did not see unix
tag till later.
/dev/random
& /dev/urandom
(@dietrich epp) provide feature.
2b 1 can use variant human reaction time like
printf("press enter\n"); unsigned u = 0; while (!keyboard_hit()) u++; srand(u);
both: combining (via exclusive-or ^
) various sources pid()
, time()
, reaction_time(), etc. helps. (see @nodakai)
even employing various mechanism prevent different seeding of random number generator, 2 different runs still generate same sequence: 1 in 20^10 (10,240,000,000,000) times per op's code. after these random numbers, coming same sequence happen.
to absolutely prevent duplication, 2 program must communicate - @ least in 1 direction. maybe ever program first write common file, sequence generated, next inspect , insure sequence makes different.
// pseudo code n = 1; repeat { srand(time()^n^pid()); n++; generate_random_number_sequence(); attempt exclusive r/w access shared file. if (file opened) { read file; if (different sequence) { write new sequence , fclose() if (no i/o errors) { done - exit } } fclose() } maybe sleep fraction of second maybe quit if repeated }
Comments
Post a Comment