抽奖之随机取值以及权重取值-java

/**
 * 随机取值-常用于随机抽卷-平等模式
 */
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));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值