权重随机算法的java实现 添加实现方法

一、概述

  平时,经常会遇到权重随机算法,从不同权重的N个元素中随机选择一个,并使得总体选择结果是按照权重分布的。如广告投放、负载均衡等。

  如有4个元素A、B、C、D,权重分别为1、2、3、4,随机结果中A:B:C:D的比例要为1:2:3:4。

  总体思路:累加每个元素的权重A(1)-B(3)-C(6)-D(10),则4个元素的的权重管辖区间分别为[0,1)、[1,3)、[3,6)、[6,10)。然后随机出一个[0,10)之间的随机数。落在哪个区间,则该区间之后的元素即为按权重命中的元素。

  实现方法

利用TreeMap,则构造出的一个树为:
    B(3)
    /      \
        /         \
     A(1)     D(10)
               /
             /
         C(6)

然后,利用treemap.tailMap().firstKey()即可找到目标元素。

当然,也可以利用数组+二分查找来实现。

二、源码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

package com.xxx.utils;

 

import com.google.common.base.Preconditions;

import org.apache.commons.math3.util.Pair;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

import java.util.List;

import java.util.SortedMap;

import java.util.TreeMap;

 

 

public class WeightRandom<K,V extends Number> {

    private TreeMap<Double, K> weightMap = new TreeMap<Double, K>();

    private static final Logger logger = LoggerFactory.getLogger(WeightRandom.class);

 

    public WeightRandom(List<Pair<K, V>> list) {

        Preconditions.checkNotNull(list, "list can NOT be null!");

        for (Pair<K, V> pair : list) {

            double lastWeight = this.weightMap.size() == 0 0 this.weightMap.lastKey().doubleValue();//统一转为double

            this.weightMap.put(pair.getValue().doubleValue() + lastWeight, pair.getKey());//权重累加

        }

    }

 

    public K random() {

        double randomWeight = this.weightMap.lastKey() * Math.random();

        SortedMap<Double, K> tailMap = this.weightMap.tailMap(randomWeight, false);

        return this.weightMap.get(tailMap.firstKey());

    }

 

}

  这是我更改之后的,服务器不支持Pair类 (采用entrySet遍历key+value的效率要高于keySet,大数据时更明显,具体比较见https://blog.csdn.net/u013776390/article/details/83106606


package app.sjgj.utils;

import com.google.common.base.Preconditions;

import java.util.*;

public class ServiceRandom<K,V extends Number> {
    private TreeMap<Double, K> weightMap = new TreeMap<Double, K>();

    public ServiceRandom(List<Map<K,V>> list) {
        Preconditions.checkNotNull(list, "list can NOT be null!");

        //获取key和value
        for (Map<K, V> map:list){
            Iterator<Map.Entry<K, V>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry key = iterator.next();
                double lastWeight = this.weightMap.size() == 0 ? 0 : this.weightMap.lastKey().doubleValue();//统一转为double
                this.weightMap.put(Double.parseDouble(key.getValue().toString()) + lastWeight, (K)key.getKey());//权重累加
            }
        }
    }

    public K random() {
        double randomWeight = this.weightMap.lastKey() * Math.random();
        SortedMap<Double, K> tailMap = this.weightMap.tailMap(randomWeight, false);
        return this.weightMap.get(tailMap.firstKey());
    }



}

  

三、性能

4个元素A、B、C、D,其权重分别为1、2、3、4,运行1亿次,结果如下:

元素命中次数误差率
A100042960.0430%
B199911320.0443%
C300008820.0029%
D400036900.0092%

从结果,可以看出,准确率在99.95%以上。

 

四、另一种实现

利用B+树的原理。叶子结点存放元素,非叶子结点用于索引。非叶子结点有两个属性,分别保存左右子树的累加权重。如下图:

看到这个图,聪明的你应该知道怎么随机了吧。

此方法的优点是:更改一个元素,只须修改该元素到根结点那半部分的权值即可。

end

作者:水岩

    

出处:http://www.cnblogs.com/waterystone/

    

本博客中未标明转载的文章归作者水岩和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 

调用的时候我是这样写的

public  Object addserviceid(Integer cityid)  {


		List<Pair<Integer, BigDecimal>> list = new ArrayList<>();
		List<SjgjServicecity> list1 = sjgjServicecityMapper.selectByCity(cityid);
		for (SjgjServicecity s:list1			 ) {

			Pair<Integer, BigDecimal> pair = new Pair<Integer, BigDecimal>(s.getServiceid(),sysinstitutionMapper.selectByPrimaryKey(s.getServiceid()).getProportion());
			list.add(pair);
		}
		WeightRandom weightRandom = new WeightRandom(list);

		return weightRandom.random();
		
	}

备忘一下    菜鸟一枚

问题来了服务器是tomcat7 不支持pair 所以用自己的办法改了一下,在源码处新贴了自己的代码,下面是调用

List<Map<Integer, BigDecimal>> list2 = new ArrayList<>();
		List<SjgjServicecity> list1 = sjgjServicecityMapper.selectByCity(171);
		for (SjgjServicecity s:list1) {
			Map<Integer, BigDecimal> map = new HashMap<Integer, BigDecimal>();

			map.put(s.getServiceid(),sysinstitutionMapper.selectByPrimaryKey(s.getServiceid()).getProportion());
			list2.add(map);
		}
		ServiceRandom serviceRandom = new ServiceRandom(list2);
		Object o =  serviceRandom.random();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
随机加权算法(Random Weighted Algorithm)是一种常见的负载均衡算法,它通过对节点进行加权,使权重越高的节点被选中的概率越大。下面是使用Go语言实现随机加权算法的示例代码: ```go import ( "math/rand" "sort" ) type WeightedNode struct { Node string Weight int } type WeightedNodeList []WeightedNode func (wl WeightedNodeList) Len() int { return len(wl) } func (wl WeightedNodeList) Less(i, j int) bool { return wl[i].Weight < wl[j].Weight } func (wl WeightedNodeList) Swap(i, j int) { wl[i], wl[j] = wl[j], wl[i] } func RandomWeightedAlgorithm(nodes []WeightedNode) string { var sum int for _, node := range nodes { sum += node.Weight } r := rand.Intn(sum) var cur int for _, node := range nodes { cur += node.Weight if cur > r { return node.Node } } // 如果所有节点权重总和为0,则返回空字符串 return "" } func RandomWeightedAlgorithmWithSort(nodes []WeightedNode) string { sort.Sort(sort.Reverse(WeightedNodeList(nodes))) return RandomWeightedAlgorithm(nodes) } ``` 代码中定义了一个 WeightedNode 结构体,包含节点名称和节点权重两个属性。WeightedNodeList 类型是一个 WeightedNode 的切片,用于存储所有节点的信息。RandomWeightedAlgorithm 函数接受一个节点列表作为参数,返回被选中的节点名称。算法首先计算所有节点权重的总和,然后生成一个 0 到总权重之间的随机数 r。接着,依次遍历节点列表,累加节点的权重值,直到累加值大于随机数 r,返回当前节点名称即可。如果所有节点权重总和为0,则返回空字符串。 另外,RandomWeightedAlgorithmWithSort 函数是在节点列表按照权重从大到小排序之后调用 RandomWeightedAlgorithm 函数,这样可以提高算法效率,因为列表已经排好序,不需要每次都计算节点权重总和。 使用示例: ```go nodes := []WeightedNode{ {Node: "node1", Weight: 2}, {Node: "node2", Weight: 3}, {Node: "node3", Weight: 5}, } selectedNode := RandomWeightedAlgorithm(nodes) fmt.Println(selectedNode) ``` 输出结果为: ``` node3 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值