Java如何制作一个权重随机数工具类呢?

书欣 Java经验 发布时间:2022-10-14 17:22:44 阅读数:4390 1
下文笔者讲述Java编写一个权重随机数工具类的方法分享,如下所示
实现思路:
    借助hutool的RandomUtil类
	即可开发一个随机数生成工具类
例:
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;
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202210/16657393994636.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者