按权重随机获取相应的数据
2016-02-02 19:22
232 查看
按照指定的权重选择不同的服务器:
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; } }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析