Bootstrap

实现一个公平的抢红包算法

具体要求:

  • 所有人抢到的金额之和要等于红包总额,不能多也不能少;
  • 每个人至少抢到1分钱;
  • 要保证红包拆分的金额尽可能分布均衡,不要出现两级分化太严重的情况。

解题思路1:二倍均值法

  • 二倍均值法保证的是每次随即金额的平均值是相等的,不会因为抢红包的先后顺序而造成不公平。具体方法如下:
  • 假设剩余红包金额为m元,剩余人数为n,那么:每次抢到的金额=随机区间[0.01,m/n×2-0.01]元

代码实现:

	 /**
     * 拆分红包
     * @param totalAmount   总金额(以分为单位)
     * @param totalPeopleNum    总人数
     * @return
     */
    public static List<Integer> divideRedPackage(Integer totalAmount,Integer totalPeopleNum){
   
        List<Integer> amountList=new ArrayList<>();
        Integer restAmount=totalAmount;
        Integer restPeopleNum=totalPeopleNum;
        Random random=new Random(
;