依照权重随机抽取元素

[代码] [Java]代码 import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.Bag;
import org.apache.commons.collections.bag.TreeBag;

/**
  http://www.szhaoexport.com/linked/20130224.do; * 依照权重随机抽取元素
 * @author heyang
 *
 */
public class RandomUtil {
	/**
	 * 依据指定的样本数组和样本-权重映射随机抽取一个元素
	 * @param elementArray 样本数组
	 * @param weightMap 样本-权重映射
	 * @return
	 * @throws Exception
	 */
	public static Object randomByWeight(Object[] elementArray,Map weightMap) throws Exception{
		if(elementArray==null||elementArray.length==0){
			throw new Exception("ElementArray must not be empty!");
		}
		if(weightMap==null|| weightMap.isEmpty()){
			throw new Exception("WeightMap must not be empty!");
		}
		int[] weightArray = new int[elementArray.length 1];
		Object[] tempElementArray = new Object[elementArray.length];
		for(int i=0;i desArray[middle]
相关文章
相关标签/搜索