I want to give the user a prize when he signs in; but it needs to be there some rare prizes so I want to appear prizes with different chances to appear using percents
i w
You can create a function to get weighted random results, something like this:
const prizes = [[50, 'flower'], [30, 'book'], [20, 'mobile']]
const total = prizes.reduce((sum, [weight]) => sum + weight, 0)
const getPrize = () => {
const rnd = Math.random() * total
let accumulator = 0
for (const [weight, item] of prizes) {
accumulator += weight
if (rnd < accumulator) {
return item
}
}
}
// check frequencies of each result
const results = {}
for (let i = 0; i < 100000; ++i) {
const prize = getPrize()
results[prize] = (results[prize] || 0) + 1
}
console.log(results)
This will work regardless of whether the weights add up to 100, whether they're integers, and so on.