基于权重的资源分布算法实现

提纲:
一、背景

二、思路

三、实现

一、背景

有的时候需要根据各种类型占用的权重来分配某种资源。如何将权重来用代码来体现呢?我觉得是个概率问题,权重越高的,在某一次资源分配的时候,能占用到资源的可能性就越高。如何用代码来表达呢?

二、思路

设想如下场景,我们将权重用百分比来表示,设想资源是一百份,权重为5%,则占用5份。

三、实现

   /**
     * 模拟基于权重的随机分布算法
     * 
     * @param args
     */
    public static void main(String[] args) {

        //100个字母装在容器组数里面,A1%  B%20  C%5  D%4  E%70  ,对应相应的5个权重
        List<String> weightArray = new ArrayList<String>();
        for (int i = 0; i < 20; i++) {
            weightArray.add("B");
        }

        for (int i = 0; i < 70; i++) {
            weightArray.add("E");
        }

        weightArray.add("A");
        weightArray.add("C");
        weightArray.add("C");
        weightArray.add("C");
        weightArray.add("C");
        weightArray.add("C");
        weightArray.add("D");
        weightArray.add("D");
        weightArray.add("D");
        weightArray.add("D");

        //获取随机数[0-99]
        int count = 0, countA = 0, countB = 0, countC = 0, countD = 0, countE = 0;
        while (true) {
            ++count;
            int index = new Random().nextInt(100);
            String s = weightArray.get(index);

            if ("A".equals(s)) {
                ++countA;
            } else if ("B".equals(s)) {
                ++countB;
            } else if ("C".equals(s)) {
                ++countC;
            } else if ("D".equals(s)) {
                ++countD;
            } else if ("E".equals(s)) {
                ++countE;
            }

            if (count % 100 == 0) {
                System.out.println("countA:" + countA + "countB:" + countB + "countC:" + countC
                                   + "countD:" + countD + "countE:" + countE);
                System.out.println("-----------------------------------------------");
                countA = 0;
                countC = 0;
                countB = 0;
                countD = 0;
                countE = 0;
            }
        }
    }
}

  不多解释了,自己看,,,

猜你喜欢

转载自kongxuan.iteye.com/blog/2021437
今日推荐