gpt4 book ai didi

javascript - 获取给定概率的伪随机项

转载 作者:行者123 更新时间:2023-12-05 02:04:51 25 4
gpt4 key购买 nike

我想在用户登录的时候给他一个奖品;但它需要有一些稀有奖品所以我想使用百分比出现不同机会的奖品

我想显示其中一个[50 : '花'], [30 : '书'], [20 : '手机'];使用他们拥有的百分比

如果有任何方法可以使用 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、是否为整数等,这都有效。

关于javascript - 获取给定概率的伪随机项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64010126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com