抢红包——二倍均值法


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RedEnvelope {
    public static void main(String[] args) {
        List<Integer> amountList = divideRedPackage(5000, 30);
        amountList.forEach(amount -> System.out.println("抢到红包:" + new BigDecimal(amount).divide(new BigDecimal(100))));
    }

    /**
     * 剩余红包金额为M,剩余人数为N,那么有如下公式:
     * 每次抢到的金额 = 随机区间 (0, M / N X 2)
     * @param totalAmount
     * @param totalPeopleNum
     * @return
     */
    private static List<Integer> divideRedPackage(int totalAmount, int totalPeopleNum) {
        List<Integer> amountList = new ArrayList<>();
        Integer restAmount = totalAmount;
        Integer restPeopleNum = totalPeopleNum;

        Random random = new Random();
        for (int i= 0; i<totalPeopleNum- 1; i++){
            //随机范围:[1,剩余人均金额的两倍),左闭右开
            int amount = random.nextInt(restAmount / restPeopleNum * 2 - 1) + 1;
            restAmount -= amount;
            restPeopleNum --;
            amountList.add(amount);
        }
        amountList.add(restAmount);
        return amountList;
    }
}


你可能感兴趣的:(抢红包——二倍均值法)