题目: 写一个以权重来进行随机分配的程序。
拿到这个题的时候我思考了一下,幸好我之前看了Ribbon 的权重算法。核心的思想就是把所有的权重值加起来,做随机值计算最终确定随机值在权重总值中的位置,从而确定是那个数据。
import java.util.ArrayList;
import java.util.List;
public class Test12 {
//权重算法
public Weight getWeight(List<Weight> list){
int totalWeight = 0;
for(Weight weight:list){
totalWeight += weight.getValue();
}
double random = Math.random();
Integer weightValue = new Double(Math.ceil(random*totalWeight)).intValue();
totalWeight = 0;
for(Weight weight:list){
totalWeight += weight.getValue();
if(weightValue - totalWeight<=0){
return weight;
}
}
return null;
}
public static void main(String[] args) {
Weight weight = new Weight(1,"A");
Weight weight2 = new Weight(2,"B");
Weight weight3 = new Weight(3,"C");
List<Weight> list = new ArrayList<>();
list.add(weight);
list.add(weight2);
list.add(weight3);
Test12 test12 = new Test12();
Weight returnWeight = test12.getWeight(list);
System.out.println(returnWeight);
}
}
class Weight{
private Integer value;
private String name;
public Weight(Integer value,String name){
this.value = value;
this.name = name;
}
public Integer getValue() {
return value;
}
}
输出结果: