如何實現搶紅包,100元6個用戶搶,每個人搶的紅包金額至少為10?


發一個紅包,要讓若干人來搶,需要滿足哪些規則?

1、所有人搶到的金額等於總金額,不能超過,也不能少於。
2、每個人至少搶到大於0的金額;
3、保證每個人搶到金額的幾率相等。比如A 搶到10元的幾率是20,B,C搶到的金額為10的幾率也是20。
本題有金額限制,每個人的金額至少是10,所以不滿足第三條規則。
這里我們設置前五個人先搶,最后那個人搶到的是總金額-5個人的金額總和。因為每個人至少搶到10元,所以前五個人的總金額不能超過90。那么每個人的平均金額就是18。
那這樣的話,極端情況下,5個人都搶到了18,最后一個人也還有10元。滿足題目條件。所以我們設置隨機數的時候就可以這樣設置。
int amount=10+random.nextInt(9);//左閉右開
也就是10 加上一個0-8之間的隨機數,9是取不到的。

代碼

    public static void main(String[] args) {
        List<Integer> lists = dividePackage(6, 100);
        for (int i = 0; i < lists.size(); i++) {
            System.out.println(lists.get(i));
        }
    }
    public static   List<Integer> dividePackage(int  peoplenum,int totalamount){
        List<Integer> amountList=new ArrayList<Integer>();
        int restAmount=totalamount;//剩余金額
        int restPeoplenum=peoplenum;//剩余人數
        Random random = new Random();
        for (int i = 0; i < peoplenum-1; i++) {

            //int amount=random.nextInt(restAmount / restPeoplenum * 2 - 1) + 1;// 0,19 +1 [0,20]
            int amount=10+(random.nextInt(8)-1)+1;//左閉右開
            restAmount = restAmount-amount;
            restPeoplenum --;

            amountList.add(amount);


        }
        amountList.add(restAmount);//加入最后的金額
        return amountList;
    }

實現結果:
14
15
11
15
14
31


免責聲明!

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



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