Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weighted Random Number Generation in C#

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.

like image 776
bugBurger Avatar asked Oct 05 '09 20:10

bugBurger


People also ask

How do you generate a random number in C?

For random number generator in C, we use rand() and srand() functions that can generate the same and different random numbers on execution.

How do you generate a random number between 1 and 10 in C?

In this program we call the srand () function with the system clock, to initiate the process of generating random numbers. And the rand () function is called with module 10 operator to generate the random numbers between 1 to 10. srand(time(0)); // Initialize random number generator.

What is RNG algorithm?

A random number generator is a hardware device or software algorithm that generates a number that is taken from a limited or unlimited distribution and outputs it. The two main types of random number generators are pseudo random number generators and true random number generators. Pseudo Random Number Generators.


1 Answers

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

if (random.NextDouble() < 0.90)
{
    BlinkGreen();
}
else
{
    BlinkRed();
}
like image 160
Michael Avatar answered Oct 16 '22 20:10

Michael