首页 > 技术文章 > Java 模板权重随机

web1992 2015-09-09 09:55 原文

      
       Template templates=...// 所有的模板
       final  int _weights=1000; // 所有的模板权重
    
       Template _template=null;
       //随机一个权重
        int rand = RandomUtil.nextInt(0, _weights);
        int lastEd = 0;
        int curEd = 0;
        // 根据随机的权重找到对应的模板
        for(Template _templ : templates) {
            int eden = _templ .getWeight();
            curEd += eden;
            if(lastEd <= rand && rand < curEd){
                _template=_templ;
                break;
            }
            lastEd += eden;
        } 

 

推荐阅读