Probability algorithm for sending props in the game

original
2014/04/21 21:27
Reading number 1.4K

Rewards must be sent to complete a certain game level, and each reward has a certain probability. The better the corresponding equipment is, the lower the probability is.
The following is a simple example of probability algorithm for reference only

 public class RateAlgorithm { public static void main(String[] args) { int index0 = 0; int index1 = 0; int index2 = 0; int index3 = 0; //Get the probability list of items double rateA[] = { 0.1, 0.2, 0.3, 0.4 }; for (int k = 0;  k < 1000; k++) { // int index = rateAlgor1(rateA); int index = rateAlgor2(rateA); if (index == 0) { index0++; } else if (index == 1) { index1++; } else if (index == 2) { index2++; } else if (index == 3) { index3++; } } System.out.println("index0=" + index0 + ",index1=" + index1 + ",index2=" + index2 + ",index3=" + index3); } /** *Probability algorithm 1 *  * @param rateA *Probability List * @return */ private static int rateAlgor1(double rateA[]) { double random = new Random().nextDouble(); for (int i = 0;  i < rateA.length; i++) { if (random <= getRate(rateA, i)) { return i; } } return rateA.length; } private static double getRate(double rateA[], int index) { double rate = 0; for (int j = 0;  j < rateA.length; j++) { if (j <= index) { rate += rateA[j]; } } return rate; } /** *Probability algorithm 2 *  * @param rateA *Probability List * @return */ private static int rateAlgor2(double rateA[]) { double random = new Random().nextDouble(); for (int i = 0;  i < rateA.length; i++) { if (random <= rateA[i]) { return i; } random -= rateA[i]; } return rateA.length; } }



Expand to read the full text
Loading
Click to lead the topic 📣 Post and join the discussion 🔥
Reward
zero comment
six Collection
zero fabulous
 Back to top
Top