Interview
Interview copied to clipboard
Day381:请实现一个抽奖函数rand,保证随机性,输入参数p表示对象数组?
对象有属性:n表示人名,w表示权重,随机返回一个中奖人名,中奖概率和w成正比。
let peoples = [
{ n: "p1", w: 100 },
{ n: "p2", w: 200 },
{ n: "p3", w: 1 },
];
let rand = function (p) {};
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 }