Get pseudo-random item with given probability

后端 未结 3 1076
终归单人心
终归单人心 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 13:20

    "Certain probability" and "random" could lead to different approaches!

    If you want random each time, something like:

    let chances = [[0.2,'mobile'],[0.5,'book'],[1.0,'flower]]
    let val = Math.random() // floating number from 0 to 1.0
    let result = chances.find( c => c[0] <= val )[1] 
    

    This will give a random result each time. It could be possible to get 'mobile' 100 times in a row! Rare, of course, but a good random number generate will let that happen.

    But perhaps you want to ensure that, in 100 results, you only hand out 20 mobiles, 30 books, and 50 flowers. Then you might want a "random array" for each user. Pre-fill the all the slots and remove them as they are used. Something like:

    // when setting up a new user
    let userArray = []
    let chances = [[20,'mobile'],[30,'book'],[50,'flower]]
    changes.forEach( c => {
      for(let i = 0; i < c[0]; i++) userArray.push(c[1])
    })
    // save userArray, which has exactly 100 values
    // then, when picking a random value for a user, find an index in the current length
    let index = Math.floor(Math.random() * userArray.length)
    let result = userArray[index]
    userArray.splice(index,1) // modify and save userArray for next login
    if(userArray.length === 0) reinitializeUserArray()
    

    There are different approaches to this, but just some ideas to get you started.

提交回复
热议问题