changing probability of getting a random number

前端 未结 7 1540
南方客
南方客 2020-12-09 22:15

I would like to generate a random number between 0 and 3 and I have the following in my code:

int random = rand() % 4;

This works fine but

7条回答
  •  旧巷少年郎
    2020-12-09 22:38

    You can use the discrete_distribution class from the random library.

    #include 
    #include 
    #include 
    
    int main()
    {
        std::discrete_distribution<> dist({ 1.0, 4.0, 4.0, 4.0 });  
        std::mt19937 eng(std::time(0));
        for (int i=0; i<100; ++i)
            std::cout << dist(eng);
    }
    

    Demo: http://ideone.com/z8bq4

    If you can't use C++11, these classes also exist in boost.

提交回复
热议问题