I. Overview
Usually, the weight of random algorithm, from the different weights of n elements randomly selected, and make the overall selection results are distributed according to the weight. such as ad delivery, load balancing and so on.
If there are 4 elements a, B, C, D, weights are 1, 2, 3, 4, the proportion of a:b:c:d in random results to be 1:2:3:4.
General idea : Add weights for each element a (1)-B (3)-C (6)-D (10), the weight of the 4 elements of the jurisdictional range is [0,1], [1,3], [3,6], [6,10]. Then randomly out a random number between [0,10]. The element that follows the interval is the element that is hit by weight.
Implementation Method :
Using TreeMap, a tree is constructed as follows:
B (3)
/ \
/ \
A (1) D (10)
/
/
C (6)
The target element can then be found using Treemap.tailmap (). Firstkey ().
Of course, you can also use array + binary lookup to implement.
Second, the source code
| 12345678910111213141516171819202122232425262728293031 |
packagecom.xxx.utils;importcom.google.common.base.Preconditions;importorg.apache.commons.math3.util.Pair;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importjava.util.List;import java.util.SortedMap;importjava.util.TreeMap;publicclassWeightRandom<K,V extendsNumber> { privateTreeMap<Double, K> weightMap = newTreeMap<Double, K>(); privatestaticfinalLogger logger = LoggerFactory.getLogger(WeightRandom.class); publicWeightRandom(List<Pair<K, V>> list) { Preconditions.checkNotNull(list, "list can NOT be null!"); for(Pair<K, V> pair : list) { doublelastWeight = this.weightMap.size() == 0? 0: this.weightMap.lastKey().doubleValue();//统一转为double this.weightMap.put(pair.getValue().doubleValue() + lastWeight, pair.getKey());//权重累加 } } publicK random() { doublerandomWeight = this.weightMap.lastKey() * Math.random(); SortedMap<Double, K> tailMap = this.weightMap.tailMap(randomWeight, false); returnthis.weightMap.get(tailMap.firstKey()); }} |
Third, performance
4 elements A, B, C, D, their weights are 1, 2, 3, 4, run 100 million times, the results are as follows:
| Elements |
Hit count |
Error rate |
| A |
10004296 |
0.043% |
| B |
19991132 |
0.0443% |
| C |
30000882 |
0.0029% |
| D |
40003690 |
0.0092% |
From the results, it can be seen that the accuracy rate is above 99.95% .
Java implementation of weighted stochastic algorithm