C # How to create a random number depends on the probabilities

I have a situation in which I have to create a random number, this number should be either zeroorone

So, the code looks something like this:

randomNumber = new Random().Next(0,1)

However, business requirements indicate that the probability of 10% of the number just generated is zero and 90% of the probability that the number generated is 1

However, can I include this probability when generating a random number?

What I was thinking:

  • Generate an array of integers including 10 zeros and 90 units.
  • Create a random index between 1 and 100
  • Take the value corresponding to this index

But I don’t know if this is the right way, plus, I think C # should have something ready for it

+4
3

:

  // Do not re-create Random! Create it once only
  // The simplest implementation - not thread-save
  private static Random s_Generator = new Random();

  ...
  // you can easiliy update the margin if you want, say, 91.234%
  const double margin = 90.0 / 100.0; 

  int result = s_Generator.NextDouble() <= margin ? 1 : 0;
+5

10%:

bool result = new Random().Next(1, 11) % 10 == 0;

40%:

bool result = new Random().Next(1, 11) > 6;
+5

, , :

Random randGen = new Random();

, , , , :

int eitherOneOrZero = randGen.Next(1, 11) % 10;

, :

Random randGen = new Random();
var trueChance = 60;

int x = randGen.Next(0, 100) < trueChance ? 1 : 0;

:

Random randGen = new Random();
var trueChance = 60;

var totalCount = 1000;
var trueCount = 0;
var falseCount = 0;

for (int i = 0; i < totalCount; i++)
{
    int x = randGen.Next(0, 100) < trueChance ? 1 : 0;

    if (x == 1)
    {
        trueCount++;
    }
    else
    {
        falseCount++;
    }
}

:

: 60,30%

: 39,70%

+2

Source: https://habr.com/ru/post/1584849/


All Articles