Java 控制随机数出现的概率
// app状态
private String appStatus[]={"system", "start", "stop" , "install", "uninstall"};
// appStatus的权重值,为以后取随机数appStatus加权重时用
private int appStatusWeight[]={1000,20,20,100,100};
/*
要使得随机数是根据权重值获得,则有两种方案可行
1、system在数组中出现1000次(即权重次数)、start出现20次、stop出现20次、 install出现100、uninstall出现100次
此方案占的内存空间大
2、1000+20+20+100+100=1240,生成随机数[0,1240),
区间[0,1000)代表system
区间[1000,1020)代表start
区间[1020,1040)代表stop
区间[1040,1140)代表install
区间[1140,1240)代表uninstall
*/
第二个方案生成新的权重值数组的方法
/**
* 循环 Int 数组中的每个值都求和 * * @param intArray [1,2,3,4,5]
* @return [1,3,6,10,15]
*/
public static List<Integer> eachIntArrayValueSum(List<Integer> intArray) {
// 当前概率最大值
Integer currentMaxWeight = 0;
// 新的概率数组,该数组的每个值都是之前的值累加的
List<Integer> newWeightList = new ArrayList<>();
for (int i = 0; i < intArray.size(); i++) {
int currentWeight = 0;
if (i == 0) {
currentMaxWeight = intArray.get(i);
currentWeight = intArray.get(i);
newWeightList.add(currentWeight);
continue;
}
// 当前最大值
currentWeight = currentMaxWeight + intArray.get(i);
currentMaxWeight = currentWeight;
newWeightList.add(currentWeight);
}
return newWeightList;
}
参考链接
本作品采用《CC 协议》,转载必须注明作者和本文链接