权重随机算法的简单实现

package suanfa;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
/**
 * 
    * @ClassName: WeightRandom
    * @Description: 简单实现权重轮询
    * @author shidebin
    * @date 2019年4月28日
    *
 */
public class WeightRandom {
	//根据机器的权重保存相同数量的机器,以保证机器出现的概率
	private static TreeMap<Integer, Integer> weightMap = new TreeMap<>();
	public static void main(String[] args) {
		pair.initWeightMap();
		int rate[] =new int[4];
		int j = 1000000;
		for(int i = 1;i<=j;i++) {
			//随机取一个值
			Integer random = new Double(weightMap.lastKey() * Math.random()).intValue();
			NavigableMap<Integer, Integer> tailMap = weightMap.tailMap(random, false);
			if(!tailMap.isEmpty()) {
				Integer value = tailMap.get(tailMap.firstKey());
				rate[value-1]++;
			}
		}
		for(int i = 0;i<=3;i++) {
			System.out.println((i+1)+"的概率是:"+new BigDecimal(rate[i]+1).divide(new BigDecimal(j)));
		}
	}
	/**
	 * 
	    * @ClassName: pair
	    * @Description: 机器权重类,如机器1的权重是0.1,2是0.2,3是0.3,4是0.4
	    * @author shidebin
	    * @date 2019年4月28日
	    *
	 */
	public static class pair{
		private Integer k;//机器
		private double v;//权重
		private static Map<Integer,Double> map;
		static {
			map  = new TreeMap<>();
			map.put(1, 0.1);
			map.put(2, 0.2);
			map.put(3, 0.3);
			map.put(4, 0.4);
		}
		/**
		 * 
		    * @Title: initWeightMap
		    * @Description: 根据权重给weightMap加值,key为重复的次数,value为机器号
		    * @param     参数
			* @author shidebin
			* @date 2019年4月28日
		    * @return void    返回类型
		    * @throws
		 */
		public static void initWeightMap() {
			int j = 1;
			for(Integer key:map.keySet()) {
				int repeat = new Double(map.get(key) * 10).intValue();
				for(int i = 1;i<= repeat;i++) {
					weightMap.put(j, key);
					j++;
				}
			}
		}
		public static int size() {
			return map.size();
		}
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值