算法原理
今天分享一篇有趣的抢红包算法,基本原理就是“二倍均值”,简单说,也就是一个公式,在这里,令P为人数,M为红包总金额,那么每次抢到的红包金额=随机区间(0,P/Mx2),这样才可以保证每次抢到随机金额的均值是相等的。
代码展示
1 package Sort_normal;
2
3 import java.math.BigDecimal;
4 import java.util.ArrayList;
5 import java.util.List;
6 import java.util.Random;
7 import java.util.Scanner;
8
9 // M:剩餘紅包
10 // N:剩餘金額
11 // 每次搶到金額:隨機區間[0,M/Nx2]
12 public class Red_Package {
13 public static void main(String[] args) {
14 Scanner in = new Scanner(System.in);
15 System.out.println("请输入红包金额:");
16 Integer TotalAmount = in.nextInt();
17 System.out.println("请输入人数:");
18 Integer TotalPeople = in.nextInt();
19 List<Integer> amountList = RedPackage(TotalAmount, TotalPeople);
20 // String[] NameList = new String[]{"小黄", "张三", "李四", "王五", "鹤叔", "丽丽", "小明", "阿杰", "媚姐", "王姨"};
21 for (Integer amount : amountList) {
22 System.out.println("搶到金額:" + new BigDecimal(amount).divide(new BigDecimal(100)) + "元");
23 }
24 }
25
26 public static List<Integer> RedPackage(Integer TotalAmount, Integer TotalPeople) {
27 List<Integer> amountList = new ArrayList<Integer>();
28 Integer restAmount = TotalAmount;//剩餘金額
29 Integer restPeople = TotalPeople;//剩餘人數
30 Random random = new Random();
31 for (int i = 0; i < TotalPeople - 1; i++) {
32 //隨機範圍:[1,剩餘人均金額的兩倍]
33 int amount = random.nextInt(restAmount / restPeople * 2 - 1) + 1;
34 restAmount -= amount;
35 restPeople--;
36 amountList.add(amount);
37 }
38 amountList.add(restAmount);
39 return amountList;
40 }
41 }
运行结果
作者:小小灰