Get a random number focused on center

后端 未结 20 3040
离开以前
离开以前 2020-12-12 09:28

Is it possible to get a random number between 1-100 and keep the results mainly within the 40-60 range? I mean, it will go out of that range rarely, but I want it to be main

20条回答
  •  猫巷女王i
    2020-12-12 09:37

    The best solution targeting this very problem is the one proposed by BlueRaja - Danny Pflughoeft but I think a somewhat faster and more general solution is also worth mentioning.


    When I have to generate random numbers (strings, coordinate pairs, etc.) satisfying the two requirements of

    1. The result set is quite small. (not larger than 16K numbers)
    2. The result set is discreet. (like integer numbers only)

    I usually start by creating an array of numbers (strings, coordinate pairs, etc.) fulfilling the requirement (In your case: an array of numbers containing the more probable ones multiple times.), then choose a random item of that array. This way, you only have to call the expensive random function once per item.

提交回复
热议问题