package Test;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
public class weight {
public static void main(String[] args) throws Exception {
weight weight = new weight();
//随机源
Map<Integer,Integer> param = new HashMap<Integer,Integer>();
Map<Integer,Integer> result = new HashMap<Integer,Integer>();
for(int i=1;i<4;i++){
param.put(i*1000, i);
}
//总权重
int totalWeights = 0;
for(Entry<Integer,Integer> entry:param.entrySet()){
totalWeights +=entry.getKey();
}
System.out.println("totalWeights="+totalWeights);
for(int i=1;i<totalWeights;i++){
int value = weight.getDataByWeight(totalWeights, param);
if(!result.containsKey(value)){
result.put(value, 1);
}else{
result.put(value, result.get(value)+1);
}
}
for(Entry<Integer, Integer> entry:result.entrySet()){
System.out.println(entry.getKey()+"------"+ Math.round(entry.getValue()/(totalWeights*1.0)*100)+"%");
}
}
public static Integer getDataByWeight(int totalWeights,Map<Integer,Integer> param ) throws Exception{
int random =new Random().nextInt(totalWeights)+1;
int tmp=0;
for(Entry<Integer,Integer> entry : param.entrySet()){
tmp=tmp+entry.getKey();
if(random<=tmp){
return entry.getValue();
}else{
continue;
}
}
return null;
}
}
随机物品权重算法DEMO
最新推荐文章于 2023-08-14 20:37:48 发布