[代碼] [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.fpjinan.com/linked/20130223.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]