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

提纲:
一、背景

二、思路

三、实现

 

 

一、背景

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

 

二、思路

设想如下场景,我们将权重用百分比来表示,设想资源是一百份,权重为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;
            }
        }
    }
}

 

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值