版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33861603/article/details/85957302
何为权重随机?
在随机的基础上增加控制抽中几率。
平时经常用到权重随机场景,比如广告投放,负载均衡,题目抽取,赌博机等
栗子:比如有24个字母A-Z,从其中取一个,默认权重都为1,则每个抽到的概率一样,此为公平的随机。
为何需要权重:
- 性能瓶颈(一般指负载均衡,相当于纵向扩展)
- 业务运维(比如广告位售价或者播放的黄金时间,这些就涉及运营了)
具体实现(代码)
1.Pair<K,V>存放key及相应的权值
/*
* @description 存储权重值跟key
* @param <K> key
* @param <V> 权值
*/
public class Pair<K,V> {
private K key;
private V value;
Pair(K key,V value){
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
2.具体算法模拟
public class WeightRandom<K,V extends Number> {
//map的key存命中次数,value存pair的key
private TreeMap<Double,K> map = new TreeMap<>();//默认升序
public WeightRandom(List<Pair<K,V>> list) {
//list.size()>1
for(Pair<K,V> p:list) {
//比如服务器A,B,C,D;比列为1:2:3:4
double lastweight = map.size()==0?0:this.map.lastKey().doubleValue();
//累加的权重为A(1),B(3),C(6),D(10),则它们各自管辖区间为[0,1),[1,3),[3,6),[6,10)
this.map.put(p.getValue().doubleValue()+ lastweight, p.getKey());//权重累加
}
}
public K random() {
double randomWeight = this.map.lastKey()*Math.random();
SortedMap<Double,K> sort = this.map.tailMap(randomWeight,false);//得到大于randomWeight的值
//如果randomWeight是4.11111111,则得到{6,10},通过firstKey(),得到6,而这个key对应C,大功告成
return this.map.get(sort.firstKey());
}
}
总结:每天进步一点!!!总有一天你能进入BAT.