Reputation: 1788
I need to make four random generated numbers which sum have to be 100. Those numbers have to be in range from 1 to 100.
How can I do this?
Upvotes: 2
Views: 3207
Reputation: 160
Already answered above, but if anyone is looking for a working example to copy and try quickly:
int main()
{
std::vector<int> v1;
int randNum1 = rand()%(97) + 1;
int randNum2 = rand()%(98-randNum1) +1;
int randNum3 = rand()%(99 - (randNum1+randNum2)) +1;
int randNum4 = 100 -(randNum1+randNum2+randNum);
v1.push_back(randNum1);
v1.push_back(randNum2);
v1.push_back(randNum3);
v1.push_back(randNum4);
int sum = 0;
for(const auto &itr : v1)
{
cout << itr <<endl;
sum =sum+itr;
}
cout << "sum is : " << sum <<endl;
return 0;
}
Upvotes: 0
Reputation: 134
Generate the first between 1 and 100-3, the second between 1 and 100-first-2, the third between 1and 100-(first+second)-1 and the fourth = 100-(first+second+third).
Upvotes: 2
Reputation: 4194
You can generate four random numbers, for example in range 0..100, then rescale them to have 100 as sum:
x_i' = 1 + x_i*96.0/sum
This solution does not provide uniform distribution of {x_i}.
@PeterWood found better answer for this question Random numbers that add to 100: Matlab
Upvotes: 6
Reputation: 950
Nothing in the problem description says that each number has to be in the range of 1 to 100. You could just vary the mod with each pass. Something like:
int sum = 0;
std::vector<int> randomNums();
while (sum != 100) {
const int randomNum = std::rand() % (99 - sum);
sum += randomNum
randomNums.push_back(randomNum);
}
Upvotes: 0
Reputation: 3571
If integer in range [1,100] (with obviusly decay to [1,97]) is what you need:
double x1 = random(0, 1);
double x2 = random(0, 1);
double x3 = random(0, 1);
double x4 = random(0, 1);
double sum = x1+x2+x3+x4;
int n1 = 1 + x1*96.0/sum;
int n2 = 1 + x2*96.0/sum;
int n3 = 1 + x3*96.0/sum;
int n4 = 100 - n1 - n2 -n3;
Upvotes: 3
Reputation: 25927
Generate first random number from range 1..97.
Then generate second random number from range 1..(98-first)
Then generate third random number from range 1..(99-(first+last))
Finally set the last number as 100 - (first+second+third)
Upvotes: 3