TreeMap implement random weights

Random weights, using the TreeMap ceilingKey Method:

/**
  * 获得给定List集合里权重大的结果
  * @param list 元素是字符串数组,第一个是权重,第二个是需要加权重的字段
  * @return
  */
 public static String getRandom(List<String[]> list){
     int total = 0;//总权重
     //以权重区间段的后面的值作为key存当前信息
     TreeMap<Integer,String> map = new TreeMap<>();
     for (String[] array : list) {
         total += Integer.parseInt(array[0]);
         map.put(total, array[1]);
     }

     int random = (int)(Math.random()*total) + 1;
     Integer key = map.ceilingKey(random);
     return map.get(key);
 }

 public static void main(String args[]) {
     long start = System.currentTimeMillis();
     String[] s1 = {"9", "1"};
     String[] s2 = {"1", "2"};
     List<String[]> list = Arrays.asList(s1, s2);
     int t = 0;
     for (int i=0; i < 10000000; i++) {
         if ("2".equals(getRandom(list))) {
             t++;
         }
     }
     System.out.println("1000万次耗时:" + (System.currentTimeMillis() - start));
     //输出命中2的次数
     System.out.println(t);
 }
复制代码

Reproduced in: https: //juejin.im/post/5cff0d2af265da1b7c610e71

Guess you like

Origin blog.csdn.net/weixin_34396103/article/details/91465039
Recommended