首页 > Web开发 > 详细

js 实现按权重随机抽奖

时间:2021-07-02 01:10:32      阅读:8      评论:0      收藏:0      [点我收藏+]

请实现抽奖函数rand,保证随机性
输入为表示对象数组,对象有属性n表示人名,w表示权重
随机返回一个中奖人名,中奖概率和w成正比

let peoples = [
  { n: ‘p1‘, w: 1 },
  { n: ‘p2‘, w: 100 },
  { n: ‘p3‘, w: 100 }
];
let rand = function (p) {
  const totalWeight = p.reduce(function (pre, cur, index) {
    cur.startW = pre;
    return cur.endW = pre + cur.w
  }, 0)
  let random = Math.ceil(Math.random() * totalWeight)
  let selectPeople = p.find(people => people.startW < random && people.endW > random)
  return selectPeople.n
};

js 实现按权重随机抽奖

原文:https://www.cnblogs.com/recode-hyh/p/14959794.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!