假设我们有一个整数16。
是否有一个函数,可以返回随机数组的数字,组成其总和?
例如7 1 2 4 1 1或1 5 2 3 6
我想知道在JavaScript中是否存在某种优雅的方法来实现这一点。
假设我们有一个整数16。
是否有一个函数,可以返回随机数组的数字,组成其总和?
例如7 1 2 4 1 1或1 5 2 3 6
我想知道在JavaScript中是否存在某种优雅的方法来实现这一点。
没有现成的函数,但是可以使用以下方法:
var n = 16;
var a = [];
while (n > 0) {
var s = Math.round(Math.random()*n);
a.push(s);
n -= s;
}
a
包含数组。
Math.round(Math.random() * (number - 1)) + 1;
。 - Ilya Tereschuk你也可以考虑这种方法
function getRandomInt(max) {
return Math.floor(Math.random() * max + 1);
}
const total = 100;
const max = 20;
const nbrounds = 9;
function fillWithRandom(max, total, len) {
let arr = new Array();
let sum = 0;
newmax = max;
do {
newtotal = total - sum;
//max depending on length
console.log(arr.length,len);
if (arr.length+1 == len) {
arr.push(newtotal);
} else {
maxbylen = parseInt(newtotal / (len - arr.length));
// console.log('maxbylen', maxbylen, arr.length);
if (max > maxbylen) {
rndmax = max;
} else {
rndmax = maxbylen;
}
if (newtotal > max) {
rnd = getRandomInt(rndmax);
} else {
rnd = getRandomInt(newtotal);
}
arr.push(rnd);
}
sum = arr.reduce((acc, val) => acc + val, 0);
// console.log('sum', sum, 'newtotal', newtotal, 'rnd', rnd, arr);
} while (sum < total);
// console.log(arr);
//random order
return arr.map((value) => ({value, sort: Math.random()})).sort((a, b) => a.sort - b.sort).map(({ value }) => value);
}
;
console.log(fillWithRandom(max, total, nbrounds));
[1..n]
中获取一个数字,其中n
是能够“完成”总和的数字,但这会导致数字分布不均匀。 - kviiri