mercredi 8 mars 2017

C++11 Mersenne Twister produces same value every time

Before you tag this as duplicate (as I'm aware that this has been asked many times) I have read through dozens of questions / answers on StackOverflow as well as many other 'tutorials' and such.

Despite following all recommendations that I'm aware of, my code produces the same "random" number every single time I run it. It doesn't look to me like I'm doing anything different to what I should be. Why isn't this working?

#include <random>
#include <iostream>
using namespace std;

random_device rd;     // used to initialise (seed) engine
mt19937 mt(rd());    // random-number engine used (Mersenne-Twister in this case)
uniform_int_distribution<int> dist(1, 4); // guaranteed unbiased

Later in code / within a function:

for (it : vec_one) {
    int rand_int = dist(mt); // Generate Random Number
    switch (rand_int) 
    {
    case 1:
        cout << "One!" << endl; 
        //Each case actually does something more interesting, 
        //but didn't fancy putting allll those lines of code on here.
    case 2:
        cout << "Two!" << endl;
    case 3:
        cout << "Three!" << endl;
    case 4:
        cout << "Four!" << endl;
    default:
        break;
    }
}

Aucun commentaire:

Enregistrer un commentaire