您的位置:首页 > 其它

mock probability with lottery

2015-09-23 12:22 363 查看
public class TestLottery {

static int BASE_RANDOM_NUM=1000;

private static int getProbabilityIndex(final List<Double> probabilityList){
Map<Integer,Double> mapRates= calculateBaseProbability(probabilityList);
int randomProbability=RandomUtils.nextInt(BASE_RANDOM_NUM);
Set<Entry<Integer, Double>>  sets=mapRates.entrySet();
for(Entry<Integer, Double> entry:sets){
if (entry.getValue() >= randomProbability && entry.getValue() <= BASE_RANDOM_NUM) {
return entry.getKey();
}
}
return -1;
}

private static Map<Integer,Double> calculateBaseProbability(final List<Double> probabilityList){
Map<Integer,Double> mapRates=new HashMap<Integer, Double>();
double sumProbability=0.0;
int index=0;
Iterator<Double> itor= probabilityList.iterator();
while(itor.hasNext()){
double probability=itor.next();
if(probability>0){
sumProbability+=probability;
mapRates.put(index, sumProbability*BASE_RANDOM_NUM);
}
index++;
}
return mapRates;
}

public static List<Double> createDoubleList(){
List<Double> orignalRates=new ArrayList<Double>();
orignalRates.add(0.0);
orignalRates.add(0.0);
orignalRates.add(0.6);
orignalRates.add(0.3);
orignalRates.add(0.1);
return orignalRates;
}

public static void main(String[] args) {
Map<Integer,Double> proMap=new HashMap<Integer, Double>();
double sumCount=100000;
List<Double> orignalRates=createDoubleList();
for (double i = 0; i < sumCount; i++) {
int index =getProbabilityIndex(orignalRates);
if(proMap.containsKey(index)){
proMap.put(index, proMap.get(index)+1.0);
}else{
proMap.put(index, 1.0);
}
}

Set<Entry<Integer, Double>> setEntry=proMap.entrySet();
for(Entry<Integer, Double> entry:setEntry){
System.out.println( entry.getKey()+"("+entry.getValue()+")->rate:"+ entry.getValue()/sumCount);
}

}
}

 

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