Random boolean with weight or bias

前端 未结 8 704
鱼传尺愫
鱼传尺愫 2020-12-01 23:42

I need to generate some random booleans. However I need to be able to specify the probability of returning true. As a results doing:

private R         


        
8条回答
  •  粉色の甜心
    2020-12-02 00:16

    Here's what I'm using. Very similar to FracturedRetina's answer.

    Random random = new Random();
    
    // 20% chance
    boolean true20 = (random.nextInt(5) == 0) ? true : false;
    
    // 25% chance
    boolean true25 = (random.nextInt(4) == 0) ? true : false;
    
    // 40% chance
    boolean true40 = (random.nextInt(5) < 2) ? true : false;
    

提交回复
热议问题