Get pseudo-random item with given probability

后端 未结 3 1079
终归单人心
终归单人心 2021-01-23 12:44

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

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 12:58

    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.

提交回复
热议问题