java中奖率算法_抽奖概率-三种算法
时间: 2023-07-10 13:06:55 浏览: 140
在Java中,有多种方式可以实现抽奖概率算法。下面介绍三种常用的算法:
1. 按照中奖概率随机抽取
这种算法最简单直接,即根据每个奖项对应的中奖概率,生成相应的随机数,然后根据随机数的大小来判断中哪个奖项。代码示例:
```java
public static int lottery(double[] probabilities) {
double sum = 0;
for (double probability : probabilities) {
sum += probability;
}
double rand = Math.random() * sum;
sum = 0;
for (int i = 0; i < probabilities.length; i++) {
sum += probabilities[i];
if (rand < sum) {
return i;
}
}
return -1;
}
```
2. 利用累加概率进行抽取
这种算法的思路是先将每个奖项的中奖概率累加起来,然后生成一个[0,1)之间的随机数,然后根据随机数在累加概率上的位置,判断中哪个奖项。代码示例:
```java
public static int lottery(double[] probabilities) {
double[] cumProbabilities = new double[probabilities.length];
cumProbabilities[0] = probabilities[0];
for (int i = 1; i < probabilities.length; i++) {
cumProbabilities[i] = cumProbabilities[i - 1] + probabilities[i];
}
double rand = Math.random();
for (int i = 0; i < cumProbabilities.length; i++) {
if (rand < cumProbabilities[i]) {
return i;
}
}
return -1;
}
```
3. 利用二分查找进行抽取
这种算法的思路是先将每个奖项的中奖概率累加起来,并且将累加概率对应的奖项编号存储在一个数组中。然后生成一个[0,1)之间的随机数,利用二分查找在累加概率数组上定位到对应的奖项编号。代码示例:
```java
public static int lottery(double[] probabilities) {
double[] cumProbabilities = new double[probabilities.length];
cumProbabilities[0] = probabilities[0];
for (int i = 1; i < probabilities.length; i++) {
cumProbabilities[i] = cumProbabilities[i - 1] + probabilities[i];
}
double rand = Math.random();
int index = Arrays.binarySearch(cumProbabilities, rand);
if (index < 0) {
index = -(index + 1);
}
return index;
}
```
这三种算法各有优缺点,可以根据实际需要选择合适的算法。
阅读全文