Java权重随机算法,根据权重随机获取一个业务对象
//AdvertPushDTO为业务对象,getWeight()获取权重值private AdvertPushDTO weightRamdom(List<AdvertPushDTO> list){ int weightSum = 0; for (AdvertPushDTO dto : list) { weightSum += dto.getWeight(); } if (weightSum <= 0) { System.err.println("错误: weightSum=" + weightSum); return null; } Integer n = new Random().nextInt(weightSum); // n的值为 [0, weightSum) Integer m = 0; for (AdvertPushDTO dto : list) { if (m <= n && n < m + dto.getWeight()) { return dto; //返回结果 } m += dto.getWeight(); } return null;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。