5

I'm trying to make a workout program that selects a random workout and musclegroup every time you start it. I have ran into trouble with selecting which musclegroup it's picking.

I would like it to pick one of the three arrays but right now the value of dice_roll is always equal to 2. Not sure where I have gone wrong. Thanks for any help.

(OBS! Excuse my ugly code, it doesn't seem to be posting right so it may be excused!)

int main() 
{
    int muscleGroup;
    string chest[2] = {"Benchpress 4x2", "Pushups 10x4"};
    string legs[2] = {"Squat 8x4", "Leg extension 10x3"};
    string back[2] = {"Pullup 3x8", "Rows 10x3"};
    mt19937 generator; 
  
    uniform_int_distribution<int> distribution(0, 2);
    int dice_roll = distribution(generator);
    if (dice_roll == 0) 
    {
        cout << "You are training: Chest" << endl;
        cout << "Your exercises are going to be written below!" << endl;
    } 
    else if (dice_roll == 1) 
    {
        cout << "You are training: Legs" << endl;
        cout << "Your exercises are going to be written below!" << endl;
    } 
    else if (dice_roll == 2) 
    {
        cout << "You are training: Back" << endl;
        cout << "Your exercises are going to be written below!" << endl;
    }         
  
    // cin >> test;
    return 0;
} 
1
  • You need to seed the generator. Easy and ugly way is mt19937 generator(time(0)); Commented Jan 1, 2018 at 13:19

1 Answer 1

5

You need to initialize your generator with a random seed.

You can do so using:

std::random_device rd;  //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()

You can find a larger code snippet and more details on the cppreference uniform_int_distribution page

Sign up to request clarification or add additional context in comments.

3 Comments

Note that it won't work on MinGW, since their random_device always produces a same sequence.
It worked doing that! Thanks a lot, i'll have to do some reading on seeds because I have no clue why it worked.
@Alexanderrost the seed is what determines the sequence of the pseudo-random generator (in your case, the mersenne twister) - you can think of it as a "starting point". Given the same seed it will always produce the same sequence of numbers (which can be very useful). Seeding it with pure entropy guarantees a unique sequence every run.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.