工作中要实现后端控制抽奖结果:
public class Test {
public static void main(String[] args) {
//奖品名称
List<String> strings = new ArrayList<>();
strings.add("特等奖");
strings.add("一等奖");
strings.add("二等奖");
strings.add("三等奖");
// 每个奖品对应的概率
List<Double> probabilities = new ArrayList<>();
//获取奖品集合
List<Integer> prizes = new ArrayList<>();
//变成百分数%
List<String> list = new ArrayList<>();
prizes.add(5);
prizes.add(10);
prizes.add(20);
prizes.add(40);
BigDecimal totalWeight = new BigDecimal(75);
if (prizes != null && prizes.size() > 0) {
BigDecimal sum = new BigDecimal(0);
for (int i = 0; i < prizes.size() - 1; i++) {
//计算概率
double divide = (new BigDecimal(prizes.get(i)).divide(totalWeight, 4, BigDecimal.ROUND_HALF_UP)).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue();
probabilities.add(divide);
//变成百分号
BigDecimal multiply = new BigDecimal(divide).multiply(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP);
list.add(multiply+"%");
sum = sum.add(new BigDecimal(divide)).setScale(4, BigDecimal.ROUND_HALF_UP);
}
//计算最后一个概率
double lastNum = (new BigDecimal(1).subtract(sum)).doubleValue();
probabilities.add(lastNum);
//变成百分号
BigDecimal multiply1 = new BigDecimal(lastNum).multiply(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP);
list.add(multiply1+"%");
}
System.out.println("百分比:"+list);
System.out.println("保留四位小数:"+probabilities);
//后台抽奖
Random random = new Random();// 随机数生成器
double luckyNum = random.nextDouble();// 生成0-1之间的随机数
double start = 0;// 概率区间起点
double end = 0;// 概率区间终点
String prize = null;// 中奖奖品
for (int i = 0; i < probabilities.size(); i++) {// 遍历每个奖品的概率
// 计算概率区间
end += probabilities.get(i);
// 判断随机数是否在当前概率区间内
if (luckyNum >= start && luckyNum < end) {
prize = strings.get(i);
break;
}
// 更新概率区间起点
start = end;
}
System.out.println("奖品结果:"+prize);
}
}
注:概率变成百分数时要转换,相乘的时候要注意精度丢失的问题。
结果如下图: