完成某个游戏关卡要发送奖励,而每种奖励都有一定的概率,相应的装备越好,概率就越低。
以下是一个简单的概率算法实例,仅供参考
public class RateAlgorithm {
public static void main(String[] args) {
int index0 = 0;
int index1 = 0;
int index2 = 0;
int index3 = 0;
// 获取道具的概率列表
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);
}
/**
* 概率算法1
*
* @param rateA
* 概率列表
* @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;
}
/**
* 概率算法2
*
* @param rateA
* 概率列表
* @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;
}
}