View Post


【数据结构和算法】之权重,百分比算法

一、权重算法

/**
     *
     * @param groupConfigMap
     *  key是要选择的对象
     *  value是这个对象的权重
     * @return
     */
    public static Long calculateGroupConfigId(Map<Long, Long> groupConfigMap) {
        if (CollectionUtils.isEmpty(groupConfigMap)) {
            return null;
        }
        Long sum = 0L;
        for (Map.Entry<Long, Long> entry : groupConfigMap.entrySet()) {
            sum += entry.getValue();
        }
        if (sum == 0L) {
            return null;
        }
        Long random = ThreadLocalRandom.current().nextLong(sum);
        Long n = 0L;
        for (Map.Entry<Long, Long> entry : groupConfigMap.entrySet()) {
            n = n + entry.getValue();
            if (random < n) {
                return entry.getKey();
            }
        }
        return null;
    }

View Code

 

版权声明:本文为shangxiaofei原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/shangxiaofei/articles/13399324.html