Need for predictable random generator

前端 未结 30 1055
情话喂你
情话喂你 2020-11-27 09:04

I\'m a web-game developer and I got a problem with random numbers. Let\'s say that a player has 20% chance to get a critical hit with his sword. That means, 1 out of 5 hits

30条回答
  •  清酒与你
    2020-11-27 09:31

    I would propose the following "randomly delayed putback die":

    • Maintain two arrays, one (in-array) initially filled with the values from 0 to n-1, the other (out-array) empty
    • When a result is requested:
      • return a random value from all defined values in in-array
      • move this value from in-array to out-array
      • move one random (over all elements, including the undefined!) element from out-array back into in-array

    This has the property that it will "react" more slowly the bigger n is. For example, if you want a 20% chance, setting n to 5 and hitting on a 0 is "less random" than setting n to 10 and hitting on a 0 or 1, and making it 0 to 199 out of 1000 will be almost indistinguishable from true randomness over a small sample. You will have to adjust n to your sample size.

提交回复
热议问题