Last active
December 28, 2015 16:39
-
-
Save Menencia/7530820 to your computer and use it in GitHub Desktop.
Returns an array of x random elements with the sum of X
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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