Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
如何优化根据总数生成随机数避免出现负数结果?_创想鸟

如何优化根据总数生成随机数避免出现负数结果?

如何优化根据总数生成随机数避免出现负数结果?

根据总数生成随机数的优化方法

在讨论中提到的方法面临着一个问题:当总数大于随机数总和时,最后生成的框值会变成负数。为了解决这个问题,我们可以对方法进行优化。

优化后的方法:

function filterate(list, num = 29) {  let data = list.map((item, index) => {    return Array.from({ length: Number(item.test) }).map(citem => {      return {        min: 0,        max: 0,        num: 0,      };    });  });  let max = Math.max(...list.map(i => Number(i.test)));  let value = 0;  let current = 1;  let count = list.reduce((n, i) => n + Number(i.test), 0);  for (let index = 0; index  {      if (item[index]) {        let step = num / count | 0; // 下取整        count--; // 循环计算 step,确保 step 在剩下的数据中平均分配        num -= step;        item[index].min = value + 1;        value += step;        item[index].max = value;        item[index].num =          Math.floor(Math.random() * (item[index].max - item[index].min + 1)) +          item[index].min;      }    });  }  return data;}

优化要点:

每次循环计算 step,确保 step 在剩下的数据中平均分配。每次更新 value 时,确保 value 不超过总数 num。

以上就是如何优化根据总数生成随机数避免出现负数结果?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1498580.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Package.json的exports配置:如何灵活控制模块导出?
上一篇 2025年12月19日 20:34:59
ES6多层对象解构:如何同时获取中间层和内层对象?
下一篇 2025年12月19日 20:35:14

相关推荐

发表回复

登录后才能评论
关注微信