package datastruct;
import java.util.HashMap;
import java.util.Map;
/**
权重随机数:
如 权重:8 2 11 79
权重返回的值:0 1 2 3
@author ajian005
79331356@qq.com 2014-2-16 21:12
输出结果:{2.0=184128, 11.0=348551, 79.0=1308100, 8.0=159221}
*/
public class WeightRandomTest {
private static double[] weightArrays = {8.0,2.0,11.0,79.0}; // 数组下标是要返回的值,数组值为数组下标的权重
public static void main(String[] args) {
WeightRandom weightRandom = new WeightRandom();
Map<Double, Integer> stat = new HashMap<Double, Integer>();
for (int i = 0; i < 2000000; i++) {
int weightValue = weightRandom.getWeightRandom(weightArrays);
if (weightValue < 0) {
continue;
}
System.out.println("按权重返回的随机数:" + weightValue);
if (stat.get(weightArrays[weightValue]) == null) {
stat.put(weightArrays[weightValue], 1);
} else {
stat.put(weightArrays[weightValue], stat.get(weightArrays[weightValue])+1);
}
}
System.out.println(stat);
}
}
class WeightRandom {
java.util.Random r = new java.util.Random();
private double weightArraySum(double [] weightArrays) {
double weightSum = 0;
for (double weightValue : weightArrays) {
weightSum += weightValue;
}
return weightSum;
}
public int getWeightRandom(double [] weightArrays) {
double weightSum = weightArraySum(weightArrays);
double stepWeightSum = 0;
for (int i = 0; i < weightArrays.length; i++) {
stepWeightSum += weightArrays[i];
if (Math.random() <= stepWeightSum/weightSum) {
//System.out.println(i);
return i;
}
}
System.out.println("出错误了");
return -1;
}
}