Random number with Probabilities

前端 未结 12 2195
醉梦人生
醉梦人生 2020-11-27 02:56

I am wondering what would be the best way (e.g. in Java) to generate random numbers within a particular range where each number has a certain probability to occur or not?

12条回答
  •  遥遥无期
    2020-11-27 03:10

    there is one more effective way rather than getting into fractions or creating big arrays or hard coding range to 100

    in your case array becomes int[]{2,3,5} sum = 10 just take sum of all the probablity run random number generator on it result = New Random().nextInt(10)

    iterate over array elements from index 0 and calculate sum and return when sum is greater than return element of that index as a output

    i.e if result is 6 then it will return index 2 which is no 5

    this solution will scale irrespective of having big numbers or size of the range

提交回复
热议问题