-4

I need a pseudo-random number generator for a c++ application, that will return me the same values in an number interval [0, 20] every time I execute the application. The requests are applied inside a loop while the application is running. For debug reasons, I need a deterministic sequence of numbers.

Thank you very much in advance

roni
  • 89
  • 1
  • 11

3 Answers3

4

The output of rand is pseudo-random, which means that it looks effectively random, but is computed the same way each time, starting from a special value called the seed. With the same seed value, you get the same sequence of random numbers.

To set a different seed, use the standard C function void srand(unsigned int) once in your code before you start generating random numbers.

Also take a look at:

Community
  • 1
  • 1
manlio
  • 18,345
  • 14
  • 76
  • 126
1

You just need to use the same seed for the random function each time. For example :

#include <stdlib.h>
#include <stdio.h>
int main ()
{
  const int seed = 3;
  /* initialize seed, with the same seed each time: */
  srand (seed);
  printf ("%d %d %d\n", rand()%20, rand()%20, rand()%20);
  return 0;
}

Thus, you'll have the same sequence each time.

Senua
  • 543
  • 4
  • 17
0

Seed the random number generator with a known value i.e. srand(42) (the meaning of life)

Then use rand.

http://linux.die.net/man/3/rand

The maths to get in in the desired range

Ed Heal
  • 59,252
  • 17
  • 87
  • 127