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 length max
, shuffle it, and get the positions of 1,2,3,...,N
with indexOf
, 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:
function generate(max, thecount) {
var r = [];
var currsum = 0;
for(var i=0; i<thecount; i++) {
r.push(Math.random());
currsum += r[i];
}
for(var i=0; i<r.length; i++) {
r[i] = Math.round(r[i] / currsum * max);
}
return r;
}
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:
7.4 3.4 5.7 3.3
If you add them, they sum 20. But if you apply Math.round:
7 3 6 3
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:
function generate(max, thecount) {
var r = [];
var decimals = [];
var currsum = 0;
for(var i=0; i<thecount; i++) {
r.push(Math.random());
currsum += r[i];
}
var remaining = max;
for(var i=0; i<r.length; i++) {
var res = r[i] / currsum * max;
r[i] = Math.floor(res);
remaining -= r[i];
decimals.push(res - r[i]);
}
while(remaining > 0){
var maxPos = 0;
var maxVal = 0;
for(var i=0; i<decimals.length; i++){
if(maxVal < decimals[i]){
maxVal = decimals[i];
maxPos = i;
}
}
r[maxPos]++;
decimals[maxPos] = 0; // We set it to 0 so we don't give this position another one.
remaining--;
}
return r;
}