抽奖工具类代码
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author : ffff
* @date 2020/12/31 15:47
*/
public class LotteryUtil {
/**
* 抽奖
*
* @param orignalRates 原始的概率列表,保证顺序和实际物品对应
* @return 物品的索引
*/
public static int lottery(List<Double> orignalRates) {
if (orignalRates == null || orignalRates.isEmpty()) {
return -1;
}
int size = orignalRates.size();
// 计算总概率,这样可以保证不一定总概率是1
double sumRate = 0d;
for (double rate : orignalRates) {
sumRate += rate;
}
// 计算每个物品在总概率的基础下的概率情况
List<Double> sortOrignalRates = new ArrayList<Double>(size);
double tempSumRate = 0d;
for (double rate : orignalRates) {
tempSumRate += rate;
sortOrignalRates.add(tempSumRate / sumRate);
}
// 根据区块值来获取抽取到的物品索引
double nextDouble = Math.random();
sortOrignalRates.add(nextDouble);
Collections.sort(sortOrignalRates);
return sortOrignalRates.indexOf(nextDouble);
}
public static void main(String[] args) {
List<String> cardNames = Arrays.asList("财", "源", "广", "进", "牛", "气", "冲", "天");
List<Double> cardRatio = Arrays.asList(5D,15.5D,15.5D,15.5D,2D,15.5D,15.5D,15.5D);
List<String> list = new ArrayList<>();
for (int i = 0; i <10000 ; i++) {
list.add(cardNames.get(LotteryUtil.lottery(cardRatio)));
}
Map<String, List<String>> collect = list.stream().collect(Collectors.groupingBy(item -> item));
collect.forEach((k,v)->{
System.out.println(k+":"+v.size());
});
}
}
对你有帮助,点个赞哦。