Generate Random Boolean Probability

后端 未结 7 1606
离开以前
离开以前 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:56

    For future knowledge:

    40:60 would be:

    var random = new Random();
    return random.Next(10) < 4;
    

    20:80 would be:

    var random = new Random();
    return random.Next(5) == 0
    

    and 1:1 would be:

    var random = new Random();
    return random.Next(2) == 1;
    

    Note: Just shorten the probability to the shortest variant - as for example: "random.Next(5) == 0" is quicker then "random.Next(100) <= 20 Though - if the probability changes from the user input - then it would look like:

    [ModifierByChoice] bool GetProbability(int trueProbability, int falseProbability)
    {
    var random = new Random();
    return random.Next(trueProbability, trueProbability + falseProbability) < trueProbability;
    }
    

提交回复
热议问题