/**
* 随机取值-常用于随机抽卷-平等模式
*/
public static <T> T getRandom(List<T> list){
return list.get((int)(Math.floor(Math.random()*(list.size()))));
}
/**
* 随机取值-常用于随机抽奖-权重模式
*/
public static WeightT getRandomByWeight(List<WeightT> weightList){
//进行排序
weightList.sort(Comparator.comparingInt(WeightT::getWeight ));
//定义范围
List<Integer> wList = new ArrayList<>();
wList.add(0);
//经过排序后 进行区间范围值
for(WeightT weightT:weightList){
wList.add(wList.get(wList.size()-1)+weightT.getWeight());
}
//进行随机取值
int randomData = RandomUtil.randomInt(0,wList.get(wList.size()-1));
//开始进行取值
int start,end,dataIndex = -1;
for(int i=1;i<wList.size();i++){
start = wList.get(i-1);
end = wList.get(i);
if(randomData>=start && randomData<=end){
dataIndex = i-1;
break;
}
}
if(dataIndex==-1){
return null;
}
return weightList.get(dataIndex);
}
@Data
public static class WeightT{
/**
* 权重
*/
private Integer weight;
/**
* 奖励
*/
private String reward;
}
示例使用:
public static void main(String[] args) {
List<WeightT> list = new ArrayList<>();
WeightT weightT = new WeightT();
weightT.setReward("1");
weightT.setWeight(40);
list.add(weightT);
weightT = new WeightT();
weightT.setReward("2");
weightT.setWeight(30);
list.add(weightT);
weightT = new WeightT();
weightT.setReward("3");
weightT.setWeight(20);
list.add(weightT);
weightT = new WeightT();
weightT.setReward("4");
weightT.setWeight(10);
list.add(weightT);
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<100;i++){
WeightT weightT1 = getRandomByWeight(list);
System.out.println("随机权重取值"+JSONObject.toJSONString(weightT1));
if(map.containsKey(weightT1.getWeight())){
map.put(weightT1.getWeight(),map.get(weightT1.getWeight())+1);
}else{
map.put(weightT1.getWeight(),1);
}
}
System.out.println("各级权重范围取值:"+JSONObject.toJSONString(map));
}