Coding pattern for random percentage branching?

前端 未结 7 907
再見小時候
再見小時候 2020-12-08 18:26

So let\'s say we have a code block that we want to execute 70% of times and another one 30% of times.

if(Math.random() < 0.7)
    70percentmethod();
else
         


        
7条回答
  •  死守一世寂寞
    2020-12-08 19:04

    All these answers seem quite complicated, so I'll just post the keep-it-simple alternative:

    double rnd = Math.random()
    if((rnd -= 0.6) < 0)
        60percentmethod();
    else if ((rnd -= 0.3) < 0)
        30percentmethod();
    else
        10percentmethod();
    

    Doesn't need changing other lines and one can quite easily see what happens, without digging into auxiliary classes. A small downside is that it doesn't enforce that percentages sum to 100%.

提交回复
热议问题