根據權重挑選通道的簡單演算法

來源:互聯網
上載者:User

標籤:

當存在一批通道,根據權重,選擇哪個通道去使用的簡單演算法。

利用隨機數,資料區間,來擷取通道。

通道權重越大,單位時間內使用該通道的機率會大一些。

代碼

 1 //利用了一個權重區間的比例問題,抓取隨機數的可能性,來體現權重思想 2 public static void main(String[] args) { 3     //定義三個通道的權重,按隨機數選拔使用哪個通道。 4     //A 10  B 70  C 30 5     //從資料庫查詢出list集合 6     ChannelD A=new ChannelD("A",10); 7     ChannelD B=new ChannelD("B",70); 8     ChannelD C=new ChannelD("C",30); 9     List<ChannelD> channels=new ArrayList<OrderChannelServiceImpl.ChannelD>();10     channels.add(A);11     channels.add(B);12     channels.add(C);13     14     Map<Integer,String> map=new HashMap<Integer, String>();15     Integer sum=0;//記錄權重之和16     for (ChannelD channel : channels) {17         sum+=channel.getWeight();18         map.put(sum,channel.getName());19     }20     21     Set<Integer> set=map.keySet();22     23     for (Integer integer : set) {24         Random r = new Random(System.currentTimeMillis());//隨機數25         //radom的取值區間為[0,110)26         // 10--A  80--B  110--C27         //A[0,10]佔10個值的可能   B[10,80]佔70個值的可能   C[80,110]佔30個值的可能28         //set集合是無順序的,遍曆也是無順序的。29         //餘數是隨機的。體現了權重思想。30         int radom = Math.abs(r.nextInt())%sum;//取餘31         if(integer>radom){32             String channelDName=map.get(integer);33             System.out.println("被選拔出來的通道為:"+channelDName);34         }35     }36 }37 38 class ChannelD{39     private String name;//通道名字40     private Integer weight;//權重41     42     public ChannelD(String name,Integer weight){43         this.name=name;44         this.weight=weight;45     }46 47     public String getName() {48         return name;49     }50 51     public void setName(String name) {52         this.name = name;53     }54 55     public Integer getWeight() {56         return weight;57     }58 59     public void setWeight(Integer weight) {60         this.weight = weight;61     }62     63     64     65 }
View Code

 

根據權重挑選通道的簡單演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.