权重随机数列表
时间:2019-08-10 19:10:00 分类:IT技术
随机数表
import cn.hutool.core.lang.WeightRandom;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
public class RandomUtil extends cn.hutool.core.util.RandomUtil {
/**
* 根据权重列表生成固定总量的数组
*
* @param weightList 权重列表
* @param total 随机列表数的总和
* @param fuDong 浮动指数
* @return
*/
public static <T> Map<T, Integer> randomListFromWeight(List<WeightRandom.WeightObj<T>> weightList, Integer total, double fuDong) {
if (!(fuDong > 0 && fuDong < 1)) {
throw new IllegalArgumentException("浮动指数必须在0~1之间");
}
Map<T, Integer> result = new HashMap<>();
// 将权重列表倒序排列,保证权重高的优先取值
weightList.sort(new Comparator<WeightRandom.WeightObj>() {
@Override
public int compare(WeightRandom.WeightObj o1, WeightRandom.WeightObj o2) {
if (o1.getWeight() > o2.getWeight()) {
return -1;
} else if (o1.getWeight() < o2.getWeight()) {
return 1;
} else {
return 0;
}
}
});
// 统计权重总和
double sumWeight = weightList.stream().map(WeightRandom.WeightObj::getWeight).reduce((a, b) -> a + b).orElse(1.0 * weightList.size());
// 计算平均权重
double avgWeight = sumWeight / weightList.size();
// 计算平均值
double avg = 1.0 * total / weightList.size();
int before = 0;
for (int i = 0; i < weightList.size() - 1; i++) {
// 实际值 = 平均值 * 权重 / 平均权重
double countForWeight = avg * weightList.get(i).getWeight() / avgWeight;
double min = before + countForWeight * (1 - fuDong);
double max = before + countForWeight * (1 + fuDong);
min = min > total ? before : min;
max = max > total ? total : max;
int after = min < max ? (int) Math.round(RandomUtil.randomDouble(min, max)) : total;
result.put(weightList.get(i).getObj(), after - before);
before = after;
}
// 最后一个的值
result.put(weightList.get(weightList.size() - 1).getObj(), total - before);
return result;
}
}
- 相关文章
- 热门文章
-
网站权重对网站排名的影响
2019-11-29
-
网站权重需要时间慢慢积累
2019-11-28
-
提升网站权重的方法
2019-11-28
-
为何看上去质量差的网站权重高
2019-11-28
-
企业网站优化通过哪些方面提升网站权重
2019-11-27
-
SEO外链推广,域名权重与相关性链接三者关系
2019-11-25
-
SEO外链推广,域名权重与相关性链接,谁重要?
2019-11-06
-
淘宝店铺权重查询 淘宝如何查看权重
2019-11-04
-
FAT32和NTFS最大支持的单个文件大小分别是多大?
2019-05-29
-
一步步优化JVM七:其他
2019-05-29
-
彻底关闭WINDOWS默认共享的4种方法
2019-05-29
-
教你下载被迅雷&百度云屏蔽的敏感资源
2019-05-29
-
JVM参数:-XX:ReservedCodeCacheSize
2019-05-29
-
Adobe系列全破解|Adobe Photoshop CC 2018安装破解教程
2019-05-29
-
2.session.setAttribute()和session.getAttribute()区
2019-05-29
-
渗透学习-------局域网攻击
2019-05-29