java
/**
* 生成对应的数组
*
* @param totalAmount 需要生成数组的总金额
* @param num 需要生成数字的个数
* @param min 最小的金额
* @param max 最大的金额
* @return 生成的数组
* @throws IllegalArgumentException 如果参数无效
*/
public static int[] lotteryArray(int totalAmount, int num, int min, int max) {
if (num <= 0 || min < 0 || max <= min || totalAmount < num * min) {
throw new YshopException("lotteryArray的参数无效");
}
int[] rewards = new int[num];
Random random = new Random();
int remainingAmount = totalAmount;
for (int i = 0; i < num - 1; i++) {
// 确保生成的随机数在min和max之间,并且剩余的总金额足够分配给剩余的所有奖励
int remainingRewards = num - i;
int maxPossibleReward = Math.min(remainingAmount / remainingRewards, max);
int minPossibleReward = Math.max(min, remainingAmount - (remainingRewards - 1) * max);
// 生成随机奖励
int reward = minPossibleReward + random.nextInt(maxPossibleReward - minPossibleReward + 1);
//
// if (reward>max){
// System.out.println("reward大于max:"+reward);
// }
//
// if (reward<min){
// System.out.println("reward小于min:"+reward);
// }
rewards[i] = reward;
remainingAmount -= reward;
}
// 最后一次迭代:直接设置剩余金额,确保总和正确
rewards[num - 1] = remainingAmount;
if (rewards[num - 1] < min || rewards[num - 1] > max) {
// System.out.println("最后一位数递归:"+rewards[num - 1]);
// 如果最后一个奖励小于min,这通常意味着输入参数不合理,可以递归重新计算
return lotteryArray(totalAmount, num, min, max);
}
// 确保最后生成的总金额是预期的totalAmount
if (Arrays.stream(rewards).sum() != totalAmount) {
// 如果总和不对,重新计算整个数组
// System.out.println("总数不对递归");
return lotteryArray(totalAmount, num, min, max);
}
// System.out.println("rewards:"+ Arrays.toString(rewards) +"---------");
return rewards;
}