基於權重的資源分佈算法實現

提綱:
一、背景

二、思路

三、實現

 

 

一、背景

有的時候需要根據各種類型佔用的權重來分配某種資源。如何將權重來用代碼來體現呢?我覺得是個概率問題,權重越高的,在某一次資源分配的時候,能佔用到資源的可能性就越高。如何用代碼來表達呢?

 

二、思路

設想如下場景,我們將權重用百分比來表示,設想資源是一百份,權重爲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;
            }
        }
    }
}

 

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章