Random boolean with weight or bias

前端 未结 8 718
鱼传尺愫
鱼传尺愫 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:13

    Your way is probably better, code golf-wise, but another way to do it is like this:

    public boolean getRandomBoolean() {
        Random random = new Random();
        //For 1 in 5
        int chanceOfTrue = 5;
    
        if (random.nextInt(chanceOfTrue) == 0) {
            return true;
        } else {
            return false;
        }
    }
    

    Or for 2 in 5, try this:

    public boolean getRandomBoolean() {
        Random random = new Random();
        //For 2 in 5
        int chanceOfTrue = 5;
        int randInt = random.nextInt(chanceOfTrue);
    
        if (randInt == 0 || randInt == 1) {
            return true;
        } else {
            return false;
        }
    }
    

提交回复
热议问题