Weighted Random Number Generation in C#

2019-04-27 01:29发布

Question

How can I randomly generate one of two states, with the probability of 'red' being generated 10% of the time, and 'green' being generated 90% of the time?

Background

Every 2 second either a green or a red light will blink.

This sequence will continue for 5 minutes.

The total number of occurrences of a blinking light should be 300.

8条回答
不美不萌又怎样
2楼-- · 2019-04-27 01:52

Random.NextDouble returns a number between 0 and 1, so the following should work:

if (random.NextDouble() < 0.90)
{
    BlinkGreen();
}
else
{
    BlinkRed();
}
查看更多
仙女界的扛把子
3楼-- · 2019-04-27 01:53
var random = new Random();
for (var i = 0; i < 150; ++i) {
  var red = random.Next(10) == 0;
  if (red)
    // ..
  else
    // Green
}

random.Next(10) will randomly return the numbers 0..9 and there is 10% chance of it returning 0.

查看更多
登录 后发表回答