js 实现按权重随机抽奖

时间:2021-07-02 01:10:32   收藏:0   阅读:9

请实现抽奖函数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
};

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

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!