zoukankan      html  css  js  c++  java
  • Java 从一组数据随机选择并可设置出现概率

     1 import java.util.HashMap;
     2 import java.util.Map;
     3 import java.util.Random;
     4 
     5 
     6 
     7 public class Test {
     8 
     9     //String 可以为任意类型 也可以自定义类型
    10     static Map<String, Integer> keyChanceMap = new HashMap<String,Integer>();
    11     static{
    12         keyChanceMap.put("出现比例为10的", 10);
    13         keyChanceMap.put("出现比例为100的", 100);
    14         keyChanceMap.put("出现比例为500的", 500);
    15         keyChanceMap.put("出现比例为1000的", 1000);
    16         keyChanceMap.put("出现比例为10000的", 10000);
    17     }
    18     
    19     public static void main(String[] args) {
    20         Map<String, Integer> count = new HashMap<String,Integer>();
    21         for (int i = 0; i < 100000; i++) {
    22             
    23             
    24             String item = chanceSelect(keyChanceMap);
    25             
    26             if (count.containsKey(item)) {
    27                 count.put(item, count.get(item) + 1);
    28             } else {
    29                 count.put(item, 1);
    30             }
    31         }
    32         
    33         for(String id : count.keySet()){
    34             System.out.println(id+"	出现了 "+count.get(id)+" 次");
    35         }
    36     }
    37 
    38     
    39     public static String chanceSelect(Map<String, Integer> keyChanceMap) { 
    40         if(keyChanceMap == null || keyChanceMap.size() == 0)  
    41              return null;  
    42           
    43         Integer sum = 0;  
    44         for (Integer value : keyChanceMap.values()) {  
    45              sum += value;  
    46         }  
    47         // 从1开始  
    48         Integer rand = new Random().nextInt(sum) + 1;  
    49           
    50         for (Map.Entry<String, Integer> entry : keyChanceMap.entrySet()) {
    51             rand -= entry.getValue();
    52             // 选中
    53             if (rand <= 0) {
    54                 String item = entry.getKey();
    55                 return item;
    56             }
    57         } 
    58           
    59         return null;  
    60    }
    61 }
  • 相关阅读:
    Web API框架学习——消息管道(二)
    Web API框架学习——路由(一)
    【转】Lucene.NET详细使用与优化详解
    ASP.NET MVC 创建控制器类过程
    ASP.NET MVC创建视图过程
    ORM映射设计思想
    UWP--集合绑定数据
    UWP--MVVM简单计算器
    UWP--数据绑定的几种方式
    一个自动管理学生信息的控制台应用程序(C语言)Label:Water
  • 原文地址:https://www.cnblogs.com/wiker/p/3199215.html
Copyright © 2011-2022 走看看