6

I'm a C++ newbie and I'm stumped on this. I need to call this function in my main function three times but each time it gives me the same result, i.e. pull_1, pull_2, pull_3 are the same. What do I need to do to make them actually random?

string PullOne()
{
    string pick;
    string choices[3] = {"BAR", "7", "cherries"};

    std::srand(time(0));
    pick = choices[(std::rand() % 3)];
    return pick;
}

From my main function:

string pull_1, pull_2, pull_3;
pull_1 = PullOne();
pull_2 = PullOne();
pull_3 = PullOne();
artm
  • 17,291
  • 6
  • 38
  • 54
  • BTW, if you use `rand() % 3`, you introduce a bias in the output: eg. values 0, 1, 2 don't have the same probability. See https://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator – Yann Droneaud Jul 17 '18 at 17:20

5 Answers5

17

You shouldn't call srand() before each call to rand(). Call it once – somewhere at the start of your program.

The problem is you restart the random generator so it starts to produce the very same pseudorandom sequence from the very same point.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
sharptooth
  • 167,383
  • 100
  • 513
  • 979
14

The random number generator is reset to an initial state, which is dictated by the seed value, every time you call srand. Time value may be the same between successive calls to time, hence the same seed and the same number generated.

Call seeding function (srand) only once in your main function before generating random samples.

Tugrul Ates
  • 9,451
  • 2
  • 33
  • 59
7

Why do you keep calling std::srand(time(0));? That re-seeds the PRNG.... and because this all happens within the same second, you're always re-seeding it with the same sequence.

Call srand once in your program, and once only.

Also, I would recommend, at least on POSIX-compliant systems, something like std::srand(time(0) ^ getpid()), so that you can run your program twice within the same "second" and still get a new PRNG sequence.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

The time(0) function may not have 'ticked' between function calls. So you are seeding the random number generator with the same value each time, leading to identical values for rand()

vsekhar
  • 5,090
  • 5
  • 22
  • 23
1

Your problem is that you seed the RNG each time you call the function. You should only seed this once in a program for best results. If you want the result to vary from one execution of the program to the next, srand based on the result of the time() function.

Patrick87
  • 27,682
  • 3
  • 38
  • 73