We must ensure that it is possible to have numbers such that we can achieve a minimum total number and such numbers that we cannot exceed the maximum amount.
For each number, recount its minimum and maximum values so that the estimated amount is still achievable.
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--) {
For completeness, I must point out that there are several possible ways of choosing a probability distribution. This method at least ensures that every possible combination of integers has a nonzero probability.
source share