Search code examples
c++randomnumbers

How can I set range to the random library


I really don't like the rand() function.I wanted to use the library but I don't really know how to set up a range for example from 1 to 3. I want to "random" these numbers(1,2,3) and not huge numbers like 243245.This code is how you can use the random library and print random numbers

#include <iostream>
#include <string>
#include <random>
using namespace std;
int main()
{
    minstd_rand simple_rand;

    simple_rand.seed(NULL);

    for (int ii = 0; ii < 10; ++ii)
    {
        std::cout << simple_rand() << '\n';
    }
}

Solution

  • #include <iostream>
    #include <random>
        int main()
        {
            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()
            std::uniform_int_distribution<> dis(1, 3);
    
            for (int n=0; n<10; ++n)
                //Use dis to transform the random unsigned int generated by gen into an int in [1, 6]
                std::cout << dis(gen) << ' ';
            std::cout << '\n';
        }
    

    Thanks to @holyBlackCat Credit to: cppreference.com