I want a bit of javascript that will allow me to generate 4 random numbers that add up to a certain value e.g.
if
max = 20
then
num1 = 4
num2 = 4
num3 = 7
num4 = 5
or
max = 36
then
num1 = 12
num2 = 5
num3 = 9
num4 = 10
What I have so far is...
var maxNum = 20;
var quarter;
var lowlimit;
var upplimit;
var num1 = 1000;
var num2 = 1000;
var num3 = 1000;
var num4 = 1000;
var sumnum = num1+num2+num3+num4;
quarter = maxNum * 0.25;
lowlimit = base - (base * 0.5);
upplimit = base + (base * 0.5);
if(sumnum != maxNum){
num1 = Math.floor(Math.random()*(upplimit-lowlimit+1)+lowlimit);
num2 = Math.floor(Math.random()*(upplimit-lowlimit+1)+lowlimit);
num3 = Math.floor(Math.random()*(upplimit-lowlimit+1)+lowlimit);
num4 = Math.floor(Math.random()*(upplimit-lowlimit+1)+lowlimit);
}
try this:
For my own project, I found another solution that maybe it's helpful for other people.
The idea is to let all numbers have the same probability... The first thing that came to my mind was creating an array
[1,2,3,..,N,undefined,undefined,....]
of lengthmax
, shuffle it, and get the positions of1,2,3,...,N
withindexOf
, but this was slow for big numbers.Finally I found another solution I think it's right: Create
N
random numbers between 0 and 1, and this is the part of the fraction "they want to take". If all numbers pick the same number (p.e. 1) they all will get the same value.Code, based on the solution of @devnull69:
EDIT: there's a problem with this solution with Math.round. Imagine we want 4 numbers that add up to 20, and get this numbers before doing Math.round:
If you add them, they sum 20. But if you apply Math.round:
Which they add to 18.
Then in my project, I had to do another round to give those "missing" values to the numbers that have a higher decimal fraction. This gets more complex, like:
This code will create four integers that sum up to the maximum number and will not be zero
EDIT: And this one will create
thecount
number of integers that sum up tomax
and returns them in an array (using therandombetween
function above)It was not said that the generated random numbers should all be distinct, which is e.g. impossible if the sum of the numbers should be 4.