Reputation: 123
I am trying to make this thing where it generates 7 random numbers. I am using
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function generateNum(max, thecount) {
var r = [];
var currsum = 0;
for (var i = 0; i < thecount - 1; i++) {
r[i] = getRandomInt(15, max - (thecount - i - 1) - currsum);
currsum += r[i];
}
r[thecount - 1] = max - currsum;
return r;
}
This will sometimes return numbers that are NaN
or are greater than 40 (which needs to be the max)
or less than 15 (which needs to be the min) and even less than 0.
It generates numbers that add up to another random number which is somewhere between 110 or 150.
How can I make it add up to the total random number and still be in a certain range?
Upvotes: 6
Views: 3688
Reputation: 83263
We must ensure that it is possible to have numbers such that we can reach the minimum total, and numbers such that we can not exceed the maximum total.
For each number, recalculate the its minimum and maximum value such that the intended sum is still reachable.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function randomInts(n, min, max, minSum, maxSum) {
if (min * n > maxSum || max * n < minSum) {
throw 'Impossible';
}
var ints = [];
while (n--) {
// calculate a lower bound for this number
// n * max is the max of the next n numbers
var thisMin = Math.max(min, minSum - n * max);
// calculate an upper bound for this number
// n * min is the min of the next n numbers
var thisMax = Math.min(max, maxSum - n * min);
var int = getRandomInt(thisMin, thisMax);
minSum -= int;
maxSum -= int;
ints.push(int);
}
return ints;
}
For completeness, I should point out there are several possible ways you could chose the probability distribution. This method at least ensures that every possible combination of integers has non-zero probability.
Upvotes: 3