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:
- Generate array of integer that includes 10 zeros and 90 ones.
- Generate a random index between 1 and 100
- 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
You can implement it like that:
to get true with a probability of 10%:
to get true with a probability of 40%:
First of all, you should save the reference to the random instance in order to get a proper random sequence of numbers:
The second thing to know, is that the max of the random is exclusive, so to properly solve the issue you should do:
To generalize it to any variation of chances, you can do:
Testing:
Output: