Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate N random values that sum to predetermined value?

Tags:

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?

like image 847
Wassim AZIRAR Avatar asked Apr 30 '11 15:04

Wassim AZIRAR


1 Answers

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.

like image 144
Ivan Ferić Avatar answered Sep 17 '22 14:09

Ivan Ferić