How to generate multiple random integers in C++

You may have already learned how to generate random numbers using the rand(), srand() and time() functions:
https://progressivecpp.blogspot.com/2020/03/How-to-generate-random-numbers-Cpp-rand-srand-time.htmll

However, try applying a LOOPING and generating several times, in consecutive ways: it will be a problem, it will comes out the same number!

The solution with rand() is recommended if you are going to generate a random number only once, or with spacing of several seconds, between one generation and another.

To generate several numbers in a row, up to millions, we recommend using the random library, as follows:
#include <iostream>
#include <iomanip>
#include <random>
using namespace std;

int gen_number()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 6);

    return dis(gen);
}

int main()
{
    int aux;

    for(aux=0 ; aux<1000 ; aux++)
        cout<<gen_number()<<endl;

    return 0;
}
Note that it will generate numbers from 1 to 6 (simulating a dice roll, for example).
If you want other intervals, just change (1.6) to a range you want.

Reference: https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution

No comments:

Post a Comment