Random boolean with weight or bias

前端 未结 8 698
鱼传尺愫
鱼传尺愫 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-01 23:59

    Expanding on user2495765's answer, you can make a function which takes an input ratio (as two values chance:range see code)

    public class MyRandomFuncs {
        public Random rand = new Random();
    
        boolean getBooleanAsRatio(int chance, int range) {
            int c = rand.nextInt(range + 1);
            return c > chance;
        }
    

    }

    Depending on what you intend to do, you probably don't want to initalize Random from within your method but rather use as a class variable (as in the code above) and call nextInt() from within your function.

提交回复
热议问题