package cn.com.qmth.examcloud.core.questions.starter;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Java 从一组数据随机选择并可设置出现概率
 *
 * @author pc
 */
public class ProbabilityTest {

    //String 可以为任意类型 也可以自定义类型
    static Map<Object, Integer> keyChanceMap = new HashMap<Object, Integer>();

    static {
        keyChanceMap.put("试卷A", 100);
    }

    public static void main(String[] args) {
        Map<String, Integer> count = new HashMap<String, Integer>();
        for (int i = 0; i < 100; i++) {
            String item = chanceSelect(keyChanceMap);
            if (count.containsKey(item)) {
                count.put(item, count.get(item) + 1);
            } else {
                count.put(item, 1);
            }
        }
        for (String id : count.keySet()) {
            System.out.println(id + "\t被选中了 " + count.get(id) + " 次");
        }
    }


    public static String chanceSelect(Map<Object, Integer> keyChanceMap) {
        if (keyChanceMap == null || keyChanceMap.size() == 0) {
            return null;
        }
        Integer sum = 0;
        for (Integer value : keyChanceMap.values()) {
            sum += value;
        }
        // 从1开始
        Integer rand = new Random().nextInt(sum) + 1;

        for (Map.Entry<Object, Integer> entry : keyChanceMap.entrySet()) {
            rand -= entry.getValue();
            // 选中
            if (rand <= 0) {
                String item = entry.getKey() + "";
                return item;
            }
        }

        return null;
    }
}