java正整數分成n份且每一份數值隨機分配


記錄一下,遇到一個需求,要求把總數(正整數)分成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;
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM