Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to Generate Random Number Depends on Probabilities

I have a situation in which I must generate a random number, this number must be either zero or one

So, the code is something like this:

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

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

However can I include that probability in generating the random number please?

What I thought of is:

  1. Generate array of integer that includes 10 zeros and 90 ones.
  2. Generate a random index between 1 and 100
  3. Take the value that corresponds to that index

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

like image 322
Marco Dinatsoli Avatar asked Dec 05 '22 22:12

Marco Dinatsoli


1 Answers

You can implement it like that:

  // 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;
like image 74
Dmitry Bychenko Avatar answered Dec 24 '22 13:12

Dmitry Bychenko