希望有人喜欢,哈哈
import java.math.BigDecimal;
import java.util.*;
/**
* 抽奖
*
* @author Administrator
*/
public class Lottery {
private static String lottery(Map<String, Double> map) {
TreeMap<Double, String> weightMap = new TreeMap<Double, String>();
map.forEach((k, v) -> {
//配置奖品对应中间率
double lastWeight = weightMap.size() == 0 ? 0 : weightMap.lastKey().doubleValue();
weightMap.put(v + lastWeight, k);
});
//抽奖
double randomWeight = Math.random() * weightMap.lastKey();
NavigableMap<Double, String> tailMap = weightMap.tailMap(randomWeight, false);
return weightMap.get(tailMap.firstKey());
}
//抽奖具体红包金额
private static double lotteryAward(String value){
String[] range = value.split("-");
double length = Double.parseDouble(range[1])-Double.parseDouble(range[0]);
double money = 0;
if (range.length>1){
money =Math.random()*length+Double.parseDouble(range[0]);
}else {
money =Math.random()*Double.parseDouble(range[1]);
}
BigDecimal b = new BigDecimal(money);
return b.setScale(
2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static void main(String[] args) {
Map map = new HashMap<>();
//红包范围和对应权重,概率等于权重除以总权重
map.put("0.1-0.3",90.0);
map.put("1.1-1.5",9.0);
map.put("90-100",1.0);
//抽奖次数
int lotteryNum = 10;
for (int i = 0; i < lotteryNum; i++) {
String key = lottery(map);
System.out.println(lotteryAward(key));
}
}
}