抢红包算法
####今天分享一篇有趣的抢红包算法,基本原理就是“二倍均值”,简单说,也就是一个公式,在这里,令P为人数,M为红包总金额,那么每次抢到的红包金额=随机区间(0,P/Mx2),这样才可以保证每次抢到随机金额的均值是相等的。 下面是简单的代码:
package Sort_normal;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
// M:剩餘紅包
// N:剩餘金額
// 每次搶到金額:隨機區間[0,M/Nx2]
public class Red_Package {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入红包金额:");
Integer TotalAmount = in.nextInt();
System.out.println("请输入人数:");
Integer TotalPeople = in.nextInt();
List<Integer> amountList = RedPackage(TotalAmount, TotalPeople);
// String[] NameList = new String[]{"小黄", "张三", "李四", "王五", "鹤叔", "丽丽", "小明", "阿杰", "媚姐", "王姨"};
for (Integer amount : amountList) {
System.out.println("搶到金額:" + new BigDecimal(amount).divide(new BigDecimal(100)) + "元");
}
}
public static List<Integer> RedPackage(Integer TotalAmount, Integer TotalPeople) {
List<Integer> amountList = new ArrayList<Integer>();
Integer restAmount = TotalAmount;//剩餘金額
Integer restPeople = TotalPeople;//剩餘人數
Random random = new Random();
for (int i = 0; i < TotalPeople - 1; i++) {
//隨機範圍:[1,剩餘人均金額的兩倍]
int amount = random.nextInt(restAmount / restPeople * 2 - 1) + 1;
restAmount -= amount;
restPeople--;
amountList.add(amount);
}
amountList.add(restAmount);
return amountList;
}
}
复制代码
下面是运行的结果: