Weighted random numbers

前端 未结 6 755
情书的邮戳
情书的邮戳 2020-11-22 08:50

I\'m trying to implement a weighted random numbers. I\'m currently just banging my head against the wall and cannot figure this out.

In my project (Hold\'em hand-ran

6条回答
  •  一生所求
    2020-11-22 09:22

    What I do when I need to weight numbers is using a random number for the weight.

    For example: I need that generate random numbers from 1 to 3 with the following weights:

    • 10% of a random number could be 1
    • 30% of a random number could be 2
    • 60% of a random number could be 3

    Then I use:

    weight = rand() % 10;
    
    switch( weight ) {
    
        case 0:
            randomNumber = 1;
            break;
        case 1:
        case 2:
        case 3:
            randomNumber = 2;
            break;
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
            randomNumber = 3;
            break;
    }
    

    With this, randomly it has 10% of the probabilities to be 1, 30% to be 2 and 60% to be 3.

    You can play with it as your needs.

    Hope I could help you, Good Luck!

提交回复
热议问题