源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Java实现按权重随机数

  • 时间:2022-10-31 01:08 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Java实现按权重随机数
[b]一、问题定义:[/b] 问下有一个数组,这些数组中的值都有自己的权重,怎样设计才能高效的优先取出权重高的数?? 例如:
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;      }     } 
[b]四、归纳总结:[/b] 俄罗斯轮盘赌就是积累概率来实现 按权重负载调度等
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部