拼手气红包(二倍均值法)
@SneakyThrows
public static List<Integer> redPacketGenerator(Integer amount, Integer packetNum) {
int min = 1;
int max;
// 非法参数校验
if (amount <= 0 || packetNum <= 0 || amount < packetNum) {
throw new Exception("非法参数!");
}
List<Integer> result = new ArrayList<>();
Random random = new Random();
int restAmount = amount;
int restPacketNum = packetNum;
for (int i = 0; i < packetNum - 1; i++) {
// 限制最大红包金额,保证不会出现0
max = restAmount - min * (packetNum - i);
int singleBound = restAmount / restPacketNum * 2;
int singleAmount = random.nextInt(singleBound);
singleAmount = Math.min(singleAmount, max);
singleAmount = Math.max(singleAmount, min);
restAmount -= singleAmount;
restPacketNum--;
result.add(singleAmount);
}
result.add(restAmount);
return result;
}