qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!
https://github.com/qappleh/Interview
1.14k stars 95 forks source link

Day381:请实现一个抽奖函数rand,保证随机性,输入参数p表示对象数组? #384

Open qappleh opened 3 years ago

qappleh commented 3 years ago

对象有属性:n表示人名,w表示权重,随机返回一个中奖人名,中奖概率和w成正比。

let peoples = [
  { n: "p1", w: 100 },
  { n: "p2", w: 200 },
  { n: "p3", w: 1 },
];
let rand = function (p) {};
adaex commented 3 years ago
const peoples = [
  { n: 'p1', w: 200 },
  { n: 'p2', w: 100 },
  { n: 'p3', w: 1 },
]

const rand = function (peoples) {
  // 总权重
  const weight = peoples.reduce((value, item) => value + item.w, 0)

  // 随机值
  let random = Math.floor(Math.random() * weight)

  for (const { w, n } of peoples) {
    if (random < w) return n
    random -= w
  }
}

// 测试结果
const result = { p1: 0, p2: 0, p3: 0 }
for (let i = 0; i < 1000000; i++) {
  result[rand(peoples)]++
}
console.log(result)

测试3次,结果分别为,符合要求

{ p1: 3324481, p2: 6642416, p3: 33103 }
{ p1: 3323045, p2: 6644052, p3: 32903 }
{ p1: 3322656, p2: 6644415, p3: 32929 }