recent work encountered a random selection of a path according to the weight of the problem, a moment there is no good plan, referring to the experience on the Internet, the following solutions:
Ideas: 1. The sum of the weights, the (0, the weight of the song and] interval division, each weight occupies the length of the weight of the interval;
2. Generating a random number of equal probabilities in the (0, weighted sum) interval;
3. The random grumble in which interval, then the corresponding weight of the interval map is the resulting weighted random number.
1 Importjava.util.ArrayList;2 ImportJava.util.HashMap;3 Importjava.util.List;4 ImportJava.util.Map;5 ImportJava.util.Random;6 7 Public classWeightrandomtest {8 Public Static voidMain (string[] args) {9 //Data Initialization key:value= Weight: valueTenMap<integer, string> opermap=NewHashmap<integer, string>(); OneOpermap.put (5, "001001"); AOpermap.put (10, "005001"); -Opermap.put (40, "004001"); -Opermap.put (30, "006004"); theOpermap.put (15, "007003"); - - //Number of experiments - inttestcount=100000; + - //the sum of the weights + intSumweight=0; A for(map.entry<integer,string>Kv:operMap.entrySet ()) atsumweight+=Kv.getkey (); - - //randomly sampled 100,000 times -List<string> res=NewArraylist<string>(); - for(intk=0;k<testcount;k++){ - //generates a random number from 0 to Sumweight inRandom r=NewRandom (); - Doublerandnum=R.nextint (sumweight); to intStepweightsum=0; + //One traversal - for(map.entry<integer,string>KValue:operMap.entrySet ()) { theStepweightsum+=kvalue.getkey ();//interval (stepweightsum,stepweightsum+weights[i]) * if(randnum<=stepweightsum) {//Select Random Grumble the value in this interval is randomly generated with a weighted random number $ Res.add (Kvalue.getvalue ());Panax Notoginseng Break; - } the } + } A the //statistics and output of experimental results +Map<string, integer> map=NewHashmap<string, integer>(); -Map<string, string> mapp=NewHashmap<string, string>(); $ intValue=0; $ for(String key:res) { - if(Map.get (key)! =NULL){ -Value=map.get (Key) +1; the map.put (key, value); -Mapp.put (key,value*100.0/testcount+ "%");Wuyi } the Else { -Map.put (Key, 1); WuMapp.put (key,1*100.0/testcount+ "%"); - } About } $System.out.println ("Count of times:" +map); -SYSTEM.OUT.PRINTLN ("Probability statistics:" +MapP); - } - } A + Experimental Results: theCount: {005001=9977, 006004=29179, 001001=6026, 007003=14986, 004001=39832} -Probability statistics: {005001=9.977%, 006004=29.179%, 001001=6.026%, 007003=14.986%, 004001=39.832%}
Experimental results: From the experimental data, 100,000 experiments, the probability of random occurrence of each value in accordance with the corresponding weight value, remove the experimental number of cycles and experimental statistics and other ancillary space, the algorithm time complexity of O (n), the space Complexity of O (1)
Weighted random number problem--Selecting a path randomly based on weights