在 JavaScript 中将数字拆分为 4 个随机数

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 11:24:17

我们需要编写一个 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 ]

每次运行的输出预计会有所不同。


相关文章


有用资源