How to generate random numbers that are added to a specific number and generated in a range in JavaScript?

I try to do this when it generates 7 random numbers. I use

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 sometimes returns NaN numbers or greater than 40 (which should be maximum)

or less than 15 (which should be min) and even less than 0.

It generates numbers that add to another random number that is somewhere between 110 or 150.

How can I add it to the total random number and still be in a certain range?

+6
source share
1 answer

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--) { // 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 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.

+3
source

Source: https://habr.com/ru/post/986877/


All Articles