jeudi 5 janvier 2017

Random integers from a function always return the same number - why?

I'm currently learning C++ and have a question about the random_device.

I'm trying to simulate the monty hall problem. For this I need random integers to pick random doors. Therefore I tried making a function that returns random integers for this purpose.

int guessGetRandomIndex() {
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 eng(rd()); // seed the generator
    std::uniform_int_distribution<> distr(0, 2);
    return distr(eng);

However when I try to get random integers in main() I keep getting same numbers.

    vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto & j : v){
    int random = guessGetRandomIndex();
    std::cout << random << ' ';
}    
 Output: 1 1 1 1 1 etc.

However when I put the random device in the main loop and do the same there I manage to get random integers.

    std::random_device rd; // obtain a random number from hardware
std::mt19937 eng(rd()); // seed the generator
std::uniform_int_distribution<> distr(0, 2); // define the range
vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto & j : v){

    std::cout << distr(eng) << ' ';
}   

 Output: 1 2 1 2 0 1

Why is that? I'm simply trying to encapsulate the random device. I thought it would generate new random number each time the function is called similiar to Pythons random.randint but I reckon there is something else going on in C++.

Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire