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;
}
}
权重随机数列表
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 【蝴蝶效应】 蝴蝶效应:上个世纪70年代,美国一个名叫洛伦兹的气象学家在解释空气系统理论时说,亚马逊雨林一只蝴蝶...
- 1.rand()函数只能生成0到1之间的随机小数,如果想要生成0到10,0到100就rand()*相应的值。 2....
- 一般计算机的随机数都是伪随机数,以一个真随机数(随机数种子)作为初始条件,然后用一定的算法不停迭代产生随机数。Un...