您的位置:首页 > 其它

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

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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法