按照权重选择的java算法

项目中用到此业务,所以自己先写一个,使用的核心是随机函数,Random.nextInt(n),代码如下:

算法实际没有限制权重值,但是最好限制在0-10的整数值之间,否则太大的数据范围意义也不大。



import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;


public class testMain {

    public static void main(String[] args) {
        HashMap hashCh=new HashMap();
        hashCh.put("ChoiName", "王一");
        hashCh.put("Weight", 0);
        HashMap hashCh2=new HashMap();
        hashCh2.put("ChoiName", "张二");
        hashCh2.put("Weight", 1);         
        HashMap hashCh3=new HashMap();
        hashCh3.put("ChoiName", "李三");
        hashCh3.put("Weight", 5);         
        HashMap hashCh4=new HashMap();
        hashCh4.put("ChoiName", "延四");
        hashCh4.put("Weight", 2);             
        ArrayList choiceList=new ArrayList();
        
        choiceList.add(hashCh);
        choiceList.add(hashCh2);
        choiceList.add(hashCh3);
        choiceList.add(hashCh4);
        for(int i=0;i<40;i++){
            System.out.println(weightChoice(choiceList));
        }
    }
    /**
     * 将选择项和权重,按随机方法选出,输入数据结构:ChoiName 选择项名称,Weight权重(整数值,0-10,0表示不选择。10表示最高权重)
     * @param listChoice
     * @return
     */
    public static String weightChoice(ArrayList<HashMap> listChoice){
        ArrayList<HashMap<String, Comparable>> choiceList=new ArrayList<HashMap<String, Comparable>>(); //选择器列表,剔除不需要选择的选项,权重为0,不进选择列表。转变权重为上下限值。
        
        Integer minR=0,maxR=-1;    //上下限
        for(HashMap temp:listChoice){
            String ChoiName=(String )temp.get("ChoiName");
            Integer weight=(Integer) temp.get("Weight");
            if(weight==0) continue;
            minR=maxR+1;
            maxR=minR+weight-1;
            HashMap hashCh=new HashMap();
            hashCh.put("ChoiName", ChoiName);
            hashCh.put("minR", minR); //下限
            hashCh.put("maxR", maxR); //上限
            choiceList.add(hashCh);
        }
        //System.out.println(JSON.toJSON(choiceList));
        Random random = new Random();  
        int index =random.nextInt(maxR+1);  //产生大于等于0,小于maxR+1的整数
        //System.out.println(index);
        for(HashMap temp:choiceList){
            Integer mini=(Integer)temp.get("minR");
            Integer maxi=(Integer)temp.get("maxR");
            if( mini<=index && index<=maxi) {
                String choName=(String)temp.get("ChoiName");
                //System.out.println(choName);
                return choName;
            }
        }
        return "";
        
        
        
    }
    
}

============================================================

算法可能输出结果:

李三
李三
李三
李三
延四
延四
延四
李三
张二
李三
李三
李三
李三
李三
延四
张二
延四
李三
李三
李三
张二
李三
张二
张二
延四
延四
张二
李三
张二
延四
延四
李三
李三
李三
延四
李三
张二
张二
李三
李三



猜你喜欢

转载自blog.csdn.net/rishengcsdn/article/details/71108777