在 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 ]
预期输出在每次运行时都不同。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP