package com.evan; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class RedPacket { private static final int MAX = 20000; //單個紅包不能大於200元 private static final int BALANCE = 1; //平衡值,值越大越平衡,最新紅包和最大紅包的差距越小 /** * 生成隨機紅包[不包含搶] * * @param value 紅包總金額[單位分] * @param num 紅包個數 * @return */ public static List<Integer> build(int value, int num) { if (value <= 0) { throw new RuntimeException("紅包金額非法!"); } if (num <= 0 || num > value) { throw new RuntimeException("紅包份數非法!"); } if (num * MAX < value) { throw new RuntimeException("每一個紅包的金額不能大於[" + (MAX / 100) + "]元!"); } List<Integer> list = new ArrayList<Integer>(num); for (int i = 0; i < num; i++) { list.add(0); } while (value > 0) { int average = value / num / BALANCE;//BALANCE的值決定瓜分的次數,次數越多越平衡 int i = 0; while (average == 0 && value > 0) { //當剩餘金額不足以讓每一個紅包分到錢時,將剩餘金額拆成1分錢一次分給紅包直到剩餘金額爲0 //排在前面的紅包會有一分錢的固定優點,須要後期須要對全部紅包進行亂序去除這種優點 int idx = (i++) % num; int current = list.get(idx); if (current == MAX) { continue; } list.set(idx, current + 1); value--; } if (value == 0) { //當剩餘金額爲0時中止瓜分 break; } for (int idx = 0; idx < num; idx++) { int current = list.get(idx); if (current == MAX) { continue; } //從剩餘金額中隨機瓜分金額到當前紅包,Math.min(average, MAX - current)保證當前紅包的值不會超過MAX常量 int randomValue = new Random().nextInt(Math.min(average, MAX - current)) + 1; list.set(idx, current + randomValue); value = value - randomValue; if (value == 0) { break; } } } //隨機亂序 Collections.shuffle(list); return list; } public static void main(String[] args) { for (int idx = 0; idx < 20; idx++) { List<Integer> list = build(90000, 5); for (int i : list) { System.out.println(i); } System.out.println("=========="); } } }