samedi 1 juin 2019

How to generate 4 different random numbers in C++

I am making Bulls and Cows assignment from Bjarne Stroustrup's "Programming Principles and Practice Using C++" book (p. 130, exercise 13) and I want program to generate four different integers in the range 0 to 9 (e.g., 1234 but not 1122)

I made a vector to store numbers and a function which generates 4 numbers and adds them to vector, but numbers might be the same and I can't return numbers to main function

#include "../..//..//std_lib_facilities.h"

vector<int> gen4Nums(vector<int> secNum)
{
    random_device rd; // obtain a random number from hardware
    mt19937 eng(rd()); // seed the generator
    uniform_int_distribution<> distr(0, 9); // define the range 

    secNum.clear();
    for (int i = 0; i < 4; i++)
    {
        secNum.push_back(distr(eng));
        cout << secNum[i];
    }
    return secNum;
}

int main()
{
        vector<int> secNum;
        gen4Nums(secNum);   
}

I expect to return 4 different random numbers to the main function




Aucun commentaire:

Enregistrer un commentaire