Random number with Probabilities

前端 未结 12 2214
醉梦人生
醉梦人生 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:27

    You already wrote the implementation in your question. ;)

    final int ran = myRandom.nextInt(100);
    if (ran > 50) { return 3; }
    else if (ran > 20) { return 2; } 
    else { return 1; }
    

    You can speed this up for more complex implementations by per-calculating the result on a switch table like this:

    t[0] = 1; t[1] = 1; // ... one for each possible result
    return t[ran];
    

    But this should only be used if this is a performance bottleneck and called several hundred times per second.

提交回复
热议问题