Skip to content

Instantly share code, notes, and snippets.

@Menencia
Last active December 28, 2015 16:39
Show Gist options
  • Save Menencia/7530820 to your computer and use it in GitHub Desktop.
Save Menencia/7530820 to your computer and use it in GitHub Desktop.
Returns an array of x random elements with the sum of X
// Returns an array of x random elements with the sum of X
function randomArray(X, max) {
var last = -1, res = [];
while (X > 0 && res.length < max) {
var x = Math.ceil(Math.random()*X);
res.push(x);
X -= x;
last += 1;
}
if (X > 0) {
res[last] += X;
}
return res;
}
// Returns an array of x elements with the sum of X
// randomArray([6,6,8], 1)
function randomArray(arr, diff) {
var X = 0;
for (var i in arr) {
X += arr[i];
}
var nbr = Math.ceil(Math.random()*(arr.length+1));
var min = Math.min.apply(Math, arr);
var max = Math.max.apply(Math, arr);
var last = -1, res = [];
while (X > 0 && res.length < nbr) {
var x = min + Math.ceil(Math.random()*(max-min+diff)) - diff - 1;
res.push(x);
X -= x;
last += 1;
}
if (X > 0) {
res[last] = Math.min(res[last]+X, max+diff);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment