中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

權(quán)重隨機(jī)算法Java實(shí)現(xiàn)

2018-07-20    來源:open-open

容器云強(qiáng)勢上線!快速搭建集群,上萬Linux鏡像隨意使用

權(quán)重隨機(jī)算法在抽獎(jiǎng),資源調(diào)度等系統(tǒng)中應(yīng)用還是比較廣泛的,一個(gè)簡單的按照權(quán)重來隨機(jī)的實(shí)現(xiàn),權(quán)重為幾個(gè)隨機(jī)對象(分類)的命中的比例,權(quán)重設(shè)置越高命中越容易,之和可以不等于100;

簡單實(shí)現(xiàn)代碼如下:

    import java.util.ArrayList;  
    import java.util.List;  
    import java.util.Random;  
      
    public class WeightRandom {  
        static List<WeightCategory>  categorys = new ArrayList<WeightCategory>();  
        private static Random random = new Random();  
          
        public static void initData() {  
            WeightCategory wc1 = new WeightCategory("A",60);  
            WeightCategory wc2 = new WeightCategory("B",20);  
            WeightCategory wc3 = new WeightCategory("C",20);  
            categorys.add(wc1);  
            categorys.add(wc2);  
            categorys.add(wc3);  
        }  
      
        public static void main(String[] args) {  
              initData();  
              Integer weightSum = 0;  
              for (WeightCategory wc : categorys) {  
                  weightSum += wc.getWeight();  
              }  
      
              if (weightSum <= 0) {  
               System.err.println("Error: weightSum=" + weightSum.toString());  
               return;  
              }  
              Integer n = random.nextInt(weightSum); // n in [0, weightSum)  
              Integer m = 0;  
              for (WeightCategory wc : categorys) {  
                   if (m <= n && n < m + wc.getWeight()) {  
                     System.out.println("This Random Category is "+wc.getCategory());  
                     break;  
                   }  
                   m += wc.getWeight();  
              }  
      
                
        }  
      
    }  
      
    class WeightCategory {  
        private String category;  
        private Integer weight;  
          
      
        public WeightCategory() {  
            super();  
        }  
      
        public WeightCategory(String category, Integer weight) {  
            super();  
            this.setCategory(category);  
            this.setWeight(weight);  
        }  
      
      
        public Integer getWeight() {  
            return weight;  
        }  
      
        public void setWeight(Integer weight) {  
            this.weight = weight;  
        }  
      
        public String getCategory() {  
            return category;  
        }  
      
        public void setCategory(String category) {  
            this.category = category;  
        }  
    }  

標(biāo)簽: 代碼

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請與原作者聯(lián)系。

上一篇:獲得Java類屬于哪個(gè)包的代碼

下一篇:iText生成word文檔代碼示例