changing probability of getting a random number

前端 未结 7 1534
南方客
南方客 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:52

    You didn't give exact proportions, but suppose you want 1, 2, and 3 to each occur 32% of the time, and 0 to occur the other 4%. Then you could write:

    int random = rand() % 25;
    if(random > 0)
        random = random % 3 + 1;
    

    (Obviously you'd need to adjust that for different proportions. And the above is just one approach; many similar approaches could work.)

提交回复
热议问题