用Java 写一个每个中奖概率总和没有超过100% 抽奖算法
时间: 2024-02-15 09:03:06 浏览: 128
好的,以下是一个简单的Java代码实现,用于抽取一个中奖概率总和不超过100%的抽奖算法:
```
import java.util.*;
public class Lottery {
private static Random rand = new Random();
public static List<Integer> generateLottery(List<Double> probabilities, int numWinners) {
List<Integer> winners = new ArrayList<>();
double totalProb = 0.0;
for (Double prob : probabilities) {
totalProb += prob;
}
if (totalProb > 1.0) {
throw new IllegalArgumentException("Total probability cannot exceed 1.0.");
}
while (winners.size() < numWinners) {
double randNum = rand.nextDouble();
double cumulativeProb = 0.0;
for (int i = 0; i < probabilities.size(); i++) {
cumulativeProb += probabilities.get(i);
if (randNum <= cumulativeProb) {
winners.add(i);
break;
}
}
}
return winners;
}
public static void main(String[] args) {
List<Double> probabilities = Arrays.asList(0.25, 0.25, 0.5);
int numWinners = 3;
List<Integer> winners = generateLottery(probabilities, numWinners);
System.out.println("Winners: " + winners);
}
}
```
在这个实现中,我们首先计算出所有概率的总和,如果总和超过1.0,则抛出异常。然后我们使用随机数生成器来抽取中奖者,直到我们得到指定数量的中奖者。对于每个随机数,我们计算出累积概率并选择第一个超过随机数的概率对应的索引,这个索引就是中奖者的索引。最后,我们返回中奖者的索引列表。
阅读全文