在JavaScript中将数字拆分为4个随机数
我们需要编写一个JavaScript函数,该函数将一个数字作为第一个输入,将一个最大数字作为第二个输入。
函数应生成四个随机数,将它们相加后应等于提供给第一个输入的数字,并且这四个数都不应该超过作为第二个输入给出的数字。
例如-如果函数的参数是-
const n = 10; const max = 4;
然后,
const output = [3, 2, 3, 2];
是有效的组合。
请注意,允许重复数字。
示例
为此的代码将是-
const total = 10;
const max = 4;
const fillWithRandom = (max, total, len = 4) => {
let arr = new Array(len);
let sum = 0;
do {
for (let i = 0; i < len; i++) {
arr[i] = Math.random();
}
sum = arr.reduce((acc, val) => acc + val, 0);
const scale = (total − len) / sum;
arr = arr.map(val => Math.min(max, Math.round(val * scale) + 1));
sum = arr.reduce((acc, val) => acc + val, 0);
} while (sum − total);
return arr;
};
console.log(fillWithRandom(max, total));输出结果
控制台中的输出将是-
[ 3, 3, 2, 2 ]
每次运行的输出预计会有所不同。