我想在用户登录时给他一个奖品;
但它需要有一些稀有的奖品,所以我想使用百分比以不同的机会出现奖品
我想显示其中之一[50 : 'flower'], [30 : 'book'], [20 : 'mobile'];
使用他们拥有的百分比
如果有任何方法使用 Node.js 或只是 javascript 函数那就太好了
您可以创建一个函数来获取加权随机结果,如下所示:
const weightedSample = (items) => {
// cache if necessary; in Chrome, seems to make little difference
const total = Object.values(items).reduce((sum, weight) => sum + weight, 0)
const rnd = Math.random() * total
let accumulator = 0
for (const [item, weight] of Object.entries(items)) {
accumulator += weight
if (rnd < accumulator) {
return item
}
}
}
// check frequencies of each result
const prizes = { flower: 50, book: 30, mobile: 20 }
const results = Object.fromEntries(Object.keys(prizes).map(k => [k, 0]))
for (let i = 0; i < 1e6; ++i) {
const prize = weightedSample(prizes)
++results[prize]
}
// sample results: { flower: 500287, book: 299478, mobile: 200235 }
console.log(results)
无论权重加起来是否为 100、是否为整数等等,这都会起作用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)