按权重随机获取相应的数据

按照指定的权重选择不同的服务器:

public final class WeightRandomUtil {

	public static void main(String[] args) {
		List<WeightBean> list = new ArrayList<WeightBean>();
		WeightBean bean = new WeightBean("A", 6);
		WeightBean bean2 = new WeightBean("B", 0);
		WeightBean bean3 = new WeightBean("C", 1);
		WeightBean bean4 = new WeightBean("D", 1);
		WeightBean bean5 = new WeightBean("E", 1);
		list.add(bean);
		list.add(bean2);
		list.add(bean3);
		list.add(bean4);
		list.add(bean5);

		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("A", 0);
		map.put("B", 0);
		map.put("C", 0);
		map.put("D", 0);
		map.put("E", 0);
		int sum = getWeightSum(list);
		for (int i = 0; i < 1000000; i++) {
			int randomWeight = RandomUtils.nextInt(sum);
			String chooseName = getRandomObj(list, randomWeight).getName();
			int chooseCount = map.get(chooseName);
			map.put(chooseName, ++chooseCount);
		}
		for (Map.Entry<String, Integer> entry : map.entrySet()) {
			System.out.println(entry.getKey() + "..." + entry.getValue());
		}
	}

	public static <T extends WeightBean> T getRandomObj(List<T> list, Integer randomWeight) {
		Integer startInterval = NumberUtils.INTEGER_ZERO;
		T result = null;
		for (T t : list) {
			if (startInterval.intValue() <= randomWeight.intValue() && randomWeight.intValue() < startInterval.intValue() + t.getWeight().intValue()) {
				result = t;
				break;
			}
			startInterval += t.getWeight();
		}
		return result;
	}

	private static <T extends WeightBean> Integer getWeightSum(List<T> list) {
		Integer weightSum = NumberUtils.INTEGER_ZERO;
		for (T t : list) {
			weightSum += t.getWeight();
		}
		return weightSum;
	}
}

class WeightBean {
	private String name;
	private Integer weight;

	public WeightBean(String name, int weight) {
		super();
		this.name = name;
		this.weight = weight;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getWeight() {
		return weight;
	}

	public void setWeight(Integer weight) {
		this.weight = weight;
	}

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值