Java实现按权重随机数


一、问题定义:

问下有一个数组,这些数组中的值都有自己的权重,怎样设计才能高效的优先取出权重高的数??

例如:

79331356@qq.com
2014-2-16 21:12
输出结果:{2.0=184128, 11.0=348551, 79.0=1308100, 8.0=159221}
*/ 
 
public class WeightRandomTest { 
    private static double[] weightArrays = {8.0,2.0,11.0,79.0};  // 数组下标是要返回的值,数组值为数组下标的权重 
    public static void main(String[] args) { 
        WeightRandom weightRandom = new WeightRandom(); 
        Map<Double, Integer> stat = new HashMap<Double, Integer>(); 
        for (int i = 0; i < 2000000; i++) { 
            int weightValue = weightRandom.getWeightRandom(weightArrays); 
            if (weightValue < 0) { 
                continue; 
            } 
            System.out.println("按权重返回的随机数:" + weightValue); 
            if (stat.get(weightArrays[weightValue]) == null) { 
                stat.put(weightArrays[weightValue], 1); 
            } else { 
                stat.put(weightArrays[weightValue], stat.get(weightArrays[weightValue])+1); 
            } 
        } 
        System.out.println(stat); 
    } 

 
class WeightRandom { 
    java.util.Random r = new java.util.Random(); 
    private double weightArraySum(double [] weightArrays) { 
        double weightSum = 0; 
        for (double weightValue : weightArrays) { 
            weightSum += weightValue; 
        } 
        return weightSum; 
    } 
    public int getWeightRandom(double [] weightArrays) { 
        double weightSum = weightArraySum(weightArrays); 
        double stepWeightSum = 0; 
        for (int i = 0; i < weightArrays.length; i++) { 
            stepWeightSum += weightArrays[i]; 
            if (Math.random() <= stepWeightSum/weightSum) { 
                //System.out.println(i); 
                return i; 
            } 
        } 
        System.out.println("出错误了"); 
        return -1; 
    }    

四、归纳总结:

俄罗斯轮盘赌就是积累概率来实现

按权重负载调度等


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3