C++ srand() repeating the same string of numbers

Viewed 30

I'm using srand() to generate numbers from 0 to 3. My output is repeating the same combination of the four numbers and I'm not sure why or how to fix it.

#include <iostream>

int main(int argc, char** argv) {

  srand((unsigned int) time(NULL));
  
  for(int i = 0; i < 20; i++) {
    int n = std::rand() % 4;
    std::cout << n;
  }
  
  std::cout << std::endl;
  
  return 0;
}

Code output:

C:\School\ProgFund3\Int Stack>a
12301230123012301230

C:\School\ProgFund3\Int Stack>a
23012301230123012301

C:\School\ProgFund3\Int Stack>a
30123012301230123012

C:\School\ProgFund3\Int Stack>
1 Answers

The problem is, I think, due to the fact that you're compiling your code with a library that has a very basic implementation of rand(). Probably this one, in fact:

next_value = ((current_value * 1103515245) + 12345) & 0x7fffffff;

One of the problems with this function is that the low-order bits of the pseudo-random output sequence follow a very predictable pattern.

A quick fix would be to use some other bits instead, e.g.:

    int n = (std::rand() >> 16) % 4;
Related