@Test
public void test1() {
//{"list":[{"integral":500,"probability":80},{"integral":100,"probability":8},{"integral":160,"probability":4},{"integral":110,"probability":6},{"integral":190,"probability":2}],"lotteryIntegral":20}
RotaryDriveOutVO rotaryDrive = activityMainService.getRotaryDrive(ActivitySubEnum.ROTARY_PRIZE.getCode());
List<IntegralProbability> list = rotaryDrive.getList();
Map<Integer, Integer> map = new TreeMap<>();
int a = 0;
for (IntegralProbability integralProbability : list) {
if (a == 0) {
a = integralProbability.getProbability();
} else {
a += integralProbability.getProbability();
}
map.put(integralProbability.getIntegral(), a);
}
System.out.println(JSON.toJSONString(map));
List<Map.Entry<Integer, Integer>> mapList = new ArrayList<>(map.entrySet());
//利用Collections的sort方法对list排序
mapList.sort(Comparator.comparingInt(Map.Entry::getValue));
System.out.println("排序之后:" + JSON.toJSONString(mapList));
Random random = new Random();
int r = random.nextInt(99) + 1;
System.out.println("标枪:" + r);
for (Map.Entry<Integer, Integer> entry : mapList) {
if (entry.getValue() >= r) {
Integer key = entry.getKey();
System.out.println("抽中了 " + key);
break;
}
}
}
思路:区间落点,就像打靶一样,我这里是抽积分,要是抽别的可以把奖品id放到key里面,其实也可以不用排序,使用TreeMap的默认key排序,但是概率要放到key里面了,我这里是手动排序了一下。