To randomly generate nbValue in the interval [average-delta,average+delta] such that the sum of these values is equal to fullSum, I use this program
1 : nbValue-1 are randomly generated
2 : the last value is calculated (fullSum - Sum of nbValue)
3 : If the last value is not in the interval, this loop is restarted.
This is the code :
int main()
{
int fullSum = 4096, nbValue = 16;
int average = round(fullSum / nbValue);
int delta = round(average*0.125);
int tryCounter = 0;
int lastStep;
srand(time(0));
do {
int currentSum = 0;
for (int i=0;i<nbValue-1;i++)
currentSum+=rand()%(delta*2+1)-delta+average ;
tryCounter ++;
lastStep = fullSum - currentSum;
}
while ( (lastStep < average - delta) || (lastStep > average + delta) );
printf("Total tries : %d\n",tryCounter);
}
Is there a better solution to be more efficient (That means, to reduce the number of tries) ? (Rq : I want a uniform distribution on the intervall)
Thanks for answer.