Generate Random Boolean Probability

后端 未结 7 1705
离开以前
离开以前 2021-02-05 01:17

I only know how I can generate a random boolean value (true/false). The default probability is 50:50

But how can I generate a true false value with my own probability? L

7条回答
  •  耶瑟儿~
    2021-02-05 01:49

    Here is an extension method that will provide a random bool with specified probability (in percentage) of being true;

    public static bool NextBool(this Random r, int truePercentage = 50)
    {
        return r.NextDouble() < truePercentage / 100.0;
    }
    

    you can use this like

    Random r = new Random();
    r.NextBool(); // returns true or false with equal probability
    r.NextBool(20); // 20% chance to be true;
    r.NextBool(100); // always return true
    r.NextBool(0); // always return false
    

提交回复
热议问题