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.
I'm guessing you have the timing part down (so this code doesn't address that). Assuming "nice" division, this will generate 10% reds and 90% greens. If the exactness isn't important, Michael's answer already has my vote.
Building on Michaels answer, but adding further context from the question:
If you want these just to look random, you might want to implement shuffle bag
http://web.archive.org/web/20111203113141/http://kaioa.com:80/node/53
and
Need for predictable random generator
This way the blinking period should look more natural and you can simply implement the restricted number of blinks.
The other answers will definitely work if you need a random distribution that favors 90% green.
However, if you need a precise distribution, something like this will work:
Either
or
This works because
Random.Next(int maxValue)
returns a uniformly distributed integer in[0, maxValue)
andRandom.NextDouble
returns a uniformly distributeddouble
in[0, 1)
.To use: