When there is a batch of channels, according to the weights, choose which channel to use the simple algorithm.
Use the random number, the data range, to get the channel.
The greater the channel weight, the greater the probability that the channel will be used in a unit of time.
Code
1 //using the proportional problem of a weighted interval, the possibility of grasping random numbers to embody the weight thought2 Public Static voidMain (string[] args) {3 //defines the weight of three channels and selects which channel to use by random number. 4 //A ten B and C5 //querying a list collection from a database6Channeld a=NewChanneld ("A", 10);7Channeld b=NewChanneld ("B", 70);8Channeld c=NewChanneld ("C", 30);9List<channeld> channels=NewArraylist<orderchannelserviceimpl.channeld>();Ten Channels.add (A); One Channels.add (B); A Channels.add (C); - -Map<integer,string> map=NewHashmap<integer, string>(); theInteger sum=0;//record the sum of weights - for(Channeld channel:channels) { -sum+=channel.getweight (); - Map.put (Sum,channel.getname ()); + } - +Set<integer> set=Map.keyset (); A at for(Integer integer:set) { -Random r =NewRandom (System.currenttimemillis ());//Random number - //the value range of the Radom is [0,110] - //10--a 80--b 110--c - //a[0,10] A possible b[10,80 of 10 values] is possible for 70 values c[80,110] 30 values - //set sets are not sequential, and traversal is not sequential. in //the remainder is random. Embodies the weight of thought. - intRadom = Math.Abs (R.nextint ())%sum;//Take surplus to if(integer>Radom) { +String channeldname=map.get (integer); -System.out.println ("The selected channel is:" +channeldname); the } * } $ }Panax Notoginseng - classchanneld{ the PrivateString name;//Channel name + PrivateInteger weight;//Weights A the PublicChanneld (String name,integer weight) { + This. name=name; - This. weight=weight; $ } $ - PublicString GetName () { - returnname; the } - Wuyi Public voidsetName (String name) { the This. Name =name; - } Wu - PublicInteger getweight () { About returnweight; $ } - - Public voidsetweight (Integer weight) { - This. Weight =weight; A } + the - $}
View Code
A simple algorithm for selecting channels based on weights