權(quán)重隨機(jī)數(shù)列表

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 {
/**
     * 根據(jù)權(quán)重列表生成固定總量的數(shù)組
     *
     * @param weightList  權(quán)重列表
     * @param total  隨機(jī)列表數(shù)的總和
     * @param fuDong     浮動(dòng)指數(shù)
     * @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("浮動(dòng)指數(shù)必須在0~1之間");
        }
        Map<T, Integer> result = new HashMap<>();
        // 將權(quán)重列表倒序排列,保證權(quán)重高的優(yōu)先取值
        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;
                }
            }
        });
        // 統(tǒng)計(jì)權(quán)重總和
        double sumWeight = weightList.stream().map(WeightRandom.WeightObj::getWeight).reduce((a, b) -> a + b).orElse(1.0 * weightList.size());
        // 計(jì)算平均權(quán)重
        double avgWeight = sumWeight / weightList.size();
        // 計(jì)算平均值
        double avg = 1.0 * total / weightList.size();
        int before = 0;
        for (int i = 0; i < weightList.size() - 1; i++) {
            // 實(shí)際值 = 平均值 * 權(quán)重 / 平均權(quán)重
            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;
        }
        // 最后一個(gè)的值
        result.put(weightList.get(weightList.size() - 1).getObj(), total - before);
        return result;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容