Example：

80分：2个

82分：1个

85分：2个

Example：需要做一个抽奖系统，需求：抽中特等奖、一等奖、二等奖、三等奖的概率分别为1:2:3:4

 元素 最小 最大 A 0=0 1=0+1 B 1=A最大 3=A最大+2 C 3=B最大 6=B最大+3 D 6=C最大 10=C最大+4

Java代码：

/**

* 权重随机数

*/

public static int random(List<Integer> weight){

List<Integer> weightTmp = newArrayList<Integer>(weight.size()+1);

Integer sum = 0;

for( Integer d: weight ){

sum += d;

}

Random random =new Random();

int rand =random.nextInt(sum);

int index = 0;

for(int i =weightTmp.size()-1; i >0; i--){

if( rand>= weightTmp.get(i)){

index = i;

break;

}

}

return index;

}

//这只是整数权重的，如果是小数、或者百分比，可以先转化成整数，在执行这个方法

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

public class WeightRandom {

static List<WeightCategory>  categorys = new ArrayList<WeightCategory>();

private static Random random = new Random();

public static void initData() {
WeightCategory wc1 = new WeightCategory("A",60);
WeightCategory wc2 = new WeightCategory("B",20);
WeightCategory wc3 = new WeightCategory("C",20);
}

public static void main(String[] args) {

initData();

Integer weightSum = 0;

for (WeightCategory wc : categorys) {
weightSum += wc.getWeight();
}
if (weightSum <= 0) {
System.err.println("Error: weightSum=" + weightSum.toString());
return;
}

Integer n = random.nextInt(weightSum); // n in [0, weightSum)

Integer m = 0;

for (WeightCategory wc : categorys) {
if (m <= n && n < m + wc.getWeight()) {
System.out.println("This Random Category is "+wc.getCategory());
break;
}
m += wc.getWeight();

}
}
}

class WeightCategory {

private String category;

private Integer weight;

public WeightCategory() {
super();
}

public WeightCategory(String category, Integer weight) {
super();
this.setCategory(category);
this.setWeight(weight);
}

public Integer getWeight() {
return weight;
}

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

public String getCategory() {
return category;
}

public void setCategory(String category) {
this.category = category;
}

}