Skip to content

Instantly share code, notes, and snippets.

@danshan
Last active Dec 31, 2015
Embed
What would you like to do?
按概率抽奖算法
public static void main(String[] args) {
int all = 1000000;
Map<Integer, Integer> results = Maps.newHashMap();
for (int i = 0; i < all; i++) {
int id = chanceSelect(couponProbability);
if (!results.containsKey(id)) {
results.put(id, 0);
}
results.put(id, results.get(id) + 1);
}
for (int i = 91; i<=100; i++) {
System.out.println(i + ": "+ results.get(i));
}
}
private static Map<Integer, Integer> couponProbability = ImmutableMap.<Integer, Integer>builder()
.put(91, 400)
.put(92, 200)
.put(93, 150)
.put(94, 80)
.put(95, 55)
.put(96, 40)
.put(97, 30)
.put(98, 20)
.put(99, 15)
.put(100, 10)
.build();
/**
* 概率选择
* @param keyChanceMap key为唯一标识,value为该标识的概率,是去掉%的数字
* @return 被选中的key。未选中返回0
*/
public static int chanceSelect(Map<Integer, Integer> keyChanceMap) {
if (keyChanceMap == null || keyChanceMap.size() == 0) {
return 0;
}
Integer sum = 0;
for (Integer value : keyChanceMap.values()) {
sum += value;
}
// 从1开始
int rand = new Random().nextInt(sum) + 1;
for (Map.Entry<Integer, Integer> entry : keyChanceMap.entrySet()) {
rand -= entry.getValue();
// 选中
if(rand <= 0) {
return entry.getKey();
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment