public class RedPackUtils {
public static List<Integer> getRandomRedList(int sum, int count) {
if (sum <= 0 || count <= 0 || count > sum) {
throw new RunException(ECode.error, "生成随机金额列表方法调用参数不正确 sum:" + sum + ",count:" + count);
}
List<Integer> list = new ArrayList<>();
for (; count >= 1; count--) {
int money = getRandomMoney(sum, count);
sum = sum - money;
list.add(money);
}
if (sum != 0 || count != 0) {
throw new RunException(ECode.error,
"生成随机金额列表方法调用失败 sum:" + sum + ",count:" + count + ",list.size():" + list.size());
}
return list;
}
public static int getRandomMoney(int sum, int count) {
if (count == 1) {
return sum;
}
Random r = new Random();
int min = 1;
int max = sum / count * 2;
int money = r.nextInt(max);
money = money <= min ? 100 : money;
return money;
}
public static List<Integer> getRandomRedList(int totalSum, int totalCount, int min, int max) {
List<Integer> randomList = getRandomRedList(totalSum, totalCount);
int sum = 0;
for (int i = 0; i < randomList.size(); i++) {
System.out.println("第" + i + "个:" + randomList.get(i));
sum = sum + randomList.get(i);
}
System.out.println("总额:" + sum);
Collections.reverse(randomList);
for (int i = 0; i < totalCount; i++) {
Integer p = randomList.get(i);
if (p.intValue() < min) {
int chae = min - p;
addToMin(min, chae, randomList);
randomList.set(i, min);
}
}
Collections.sort(randomList);
for (int i = 0; i < totalCount; i++) {
Integer p = randomList.get(i);
if (p.intValue() > max) {
int chae = p - max;
subtractToMax(max, chae, randomList);
randomList.set(i, max);
}
}
Collections.shuffle(randomList);
sum = 0;
for (int i = 0; i < randomList.size(); i++) {
System.out.println("第" + i + "个:" + randomList.get(i));
sum = sum + randomList.get(i);
}
System.out.println("总额:" + sum);
return randomList;
}
private static void subtractToMax(int max, int chae, List<Integer> randomList) {
for (int j = 0; j < randomList.size() && chae > 0;) {
Integer current = randomList.get(j);
if (current < max) {
randomList.set(j, current + 1);
chae--;
}
j++;
if (chae > 0 && j == randomList.size()) {
j = 0;
}
}
}
private static void addToMin(int min, int chae, List<Integer> randomList) {
// 排续一下
for (int j = 0; j < randomList.size() && chae > 0;) {
Integer current = randomList.get(j);
if (current > min) {
randomList.set(j, current - 1);
chae--;
}
j++;
if (chae > 0 && j == randomList.size()) {
j = 0;
}
}
}
public static void main(String[] args) {
getRandomRedList(10000000, 500, 100, 20000);
}
}