Will rand() sometimes return the same consecutively?
c, c++, random, visual-c++
Solution
If we can find one example where it does, the answer to your question is "yes".
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
unsigned int i;
for(i = 0; ; i++) {
int r = rand();
if (r == rand()) {
printf("Oops. rand() = %d; i = %d\n", r, i);
break;
}
}
return 0;
}
prints `Oops. rand() = 3482; i = 32187` on Windows with Visual Studio 2010.
EDIT: Use the version below to detect all sequences where 2 consecutive rand() calls return the same value. C only specifies that rand() should return "pseudo-random integers in the range 0 to RAND_MAX" and RAND_MAX should be at least 32767. There are no constraints on the quality of the PRNG, or it's implementation, or other details such as whether 2 consecutive rand() calls can return the same value.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
unsigned int i;
int r1 = rand();
int r2 = rand();
for(i = 0; ; i++) {
if (r1 == r2) {
printf("Oops. rand() = %d; i = %d\n", r1, i);
}
r1 = r2;
r2 = rand();
}
return 0;
}
Problem
I'm just curious, can a single-threaded program ever get the same return value for two consecutive calls to `rand()`? So, will this assertion ever fire? ``` assert(rand() != rand()); ```