mock probability with lottery

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);
		}
		
	}
}

猜你喜欢

转载自tangzhibin.iteye.com/blog/2245509
今日推荐