Answer the question
In order to leave comments, you need to log in
How to get an array of random numbers whose sum is 500?
We need an array of positive random numbers, the sum of the elements of which will be, say, 500. The number of elements is passed as a parameter, of course, but usually there are 3 or 4 of them. No matter
how I try, there are few successes. I tried, roughly speaking, to divide 50 into parts and then multiply them by 10 and another fierce option. Well, the funniest solution is to generate until the required amount is available, poor percent.
Answer the question
In order to leave comments, you need to log in
Let's assume that the numbers are non-negative integers. If numbers can be zero, do this:
n1=irand(501); // from 0 to 500
n2=irand(501); // from 0 to 500
n3=irand(501); // from 0 to 500
sort(n1,n2,n3); // sort ascending in any suitable way
x0=n1; x1=n2-n1; x3=n3-n2; x4=500-n3;
If numbers can only be positive, then do the same:
n1=irand(497); // from 0 to 496
n2=irand(497); // from 0 to 496
n3=irand(497); // from 0 to 496
sort(n1,n2,n3); // sort ascending in any suitable way
x0=n1+1; x1=n2-n1+1; x3=n3-n2+1; x4=496-n3+1;
The distribution will be slightly uneven (sets containing zeros in the first case and ones in the second will be slightly less common), but this can be corrected by slightly complicating the program.
In your statement of the problem, there are no restrictions on the values of the elements => they can be positive and negative => you don’t need to divide anything, just fill the array with random numbers with a sign, and make one element equal to the difference between the required mum and the sum of the remaining elements.
00
Specified range of random number from A
to C
06
Remainder B + A
will be the last number
At night, looking, I threw in such a random shit code, but I think you will understand the essence
function random500() {
var n1 = Math.ceil(Math.random()*499);
var n2 = Math.ceil(Math.random()*(500-n1));
var n3 = 500 - n1 - n2;
console.log(n1 + " " + n2 + " " + n3);
}
int getRandom()
{
return 500;
}
//
// код где массив заполняется любыми числами
//
int summ = (array - array) + 500;
printf("Сумма всех чисел в массиве = %d", summ);
nachalo:
int massive[10];
int summa = 0;
for(int i = 0; i < 10; i++, array[i] = rand() % 500);
for(int i = 0; i < 10; i++, summa += array[i]);
if(summa != 500)
goto nachalo;
else if(summa == 500)
goto konec;
konec:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question