記錄一下,遇到一個需求,要求把總數(正整數)分成n份,每一份隨機分配.
public class NumberRandomSplitUtil { /** * 把一個正整數隨機拆分成count個正整數 * * @param totalNum * @param count * @return */ public static List<Integer> random(int totalNum, int count) { // 創建一個長度的紅包數組 List<Integer> redList = new ArrayList<>(); int totalMoney = (totalNum); /*if (totalMoney < count || totalMoney < 1) { return redList; // 返回空的集合 }*/ //2. 進行隨機分配 Random rand = new Random(); int leftMoney = totalMoney; // 剩余金額 int leftCount = count; // 剩余份數 // 隨機分配公式:1 + rand.nextInt(leftMoney / leftCount * 2); for (int i = 0; i < count - 1; i++) { int money_ = 0; if (leftMoney > 0) { if ((leftMoney / leftCount * 2) < 1) { money_ = leftMoney; } else { money_ = 1 + rand.nextInt(leftMoney / leftCount * 2); } } else { money_ = 0; } redList.add(money_); if (money_ > 0) { leftMoney -= money_; leftCount--; } } // 把剩余的最后一個放到最后一個包里 redList.add(leftMoney); return redList; } }