I need your help with a little problem. I have four labels and I want to display on them random value between 0 to 100, and the sum of them must be 100.
This is my code :
private void randomly_Click(object sender, EventArgs e) { double alpha = 0, beta = 0, gamma = 0, delta = 0; double temp; int tempDouble; Random rnd = new Random(); alpha = rnd.Next(0, 100); temp = 100 - alpha; tempDouble = (int)temp; beta = rnd.Next(0, tempDouble); temp = 100 - (alpha + beta); tempDouble = (int)temp; gamma = rnd.Next(0, tempDouble); temp = 100 - (alpha + beta + gamma); tempDouble = (int)temp; delta = rnd.Next(0, tempDouble); temp = alpha + beta + delta + gamma; temp = 100 - temp; temp = temp / 4; alpha = alpha + temp; beta = beta + temp; gamma = gamma + temp; delta = delta + temp; cInsertion.Text = alpha.ToString(); cMoyens.Text = beta.ToString(); cInternational.Text = gamma.ToString(); cRecherche.Text = delta.ToString(); }
The problem is that I'm giving to the alpha the chance to have the biggest
value, and for delta the lowest
value.
Is there any way to give them all the same chance to have a real random
value?
You could do something like this:
double alpha = 0, beta = 0, gamma = 0, delta = 0, k = 0; Random rnd = new Random(); alpha = rnd.Next(0, 100); beta = rnd.Next(0, 100); gamma = rnd.Next(0, 100); delta = rnd.Next(0, 100); k = (alpha + beta + gamma + delta) / 100; alpha /= k; beta /= k; gamma /= k; delta /= k; cInsertion.Text = alpha.ToString(); cMoyens.Text = beta.ToString(); cInternational.Text = gamma.ToString(); cRecherche.Text = delta.ToString();
This way you're saying let's take a random value for all 4 variables, and then we'll scale them by a factor k
that'll make their sum be 100.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With