|
| 1 | +package duoyiwangluo; |
| 2 | + |
| 3 | +import java.math.BigDecimal; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +/** |
| 7 | +* @Author: iqqcode |
| 8 | +* @Date: 2020-10-04 09:47 |
| 9 | +* @Description:线段切割法 实现公平 |
| 10 | +*/ |
| 11 | +public class _03_RedPackage { |
| 12 | +//线段分割法 |
| 13 | +private static List<Integer> getRandomMoney(int totalMoney, int amount) { |
| 14 | +//验证参数合理校验 |
| 15 | +//为了使用random.nextInt(Integer)方法, 不得不先把红包金额放大100倍,最后在main函数里面再除以100 |
| 16 | +//这样就可以保证每个人抢到的金额都可以精确到小数点后两位 |
| 17 | +int redMoney = (int) (totalMoney * 100); |
| 18 | +if (redMoney < amount || redMoney < 1) { |
| 19 | +System.out.println("红包个数必须大于0,并且最小红包不少于1分"); |
| 20 | +} |
| 21 | +List<Integer> boards = new ArrayList<>(); |
| 22 | +boards.add(0); |
| 23 | +boards.add(redMoney); |
| 24 | +//红包个数和线段个数的关系 |
| 25 | +while (boards.size() <= amount) { |
| 26 | +// 随机生成切割点 |
| 27 | +int index = new Random().nextInt(redMoney - 1) + 1; |
| 28 | +if (boards.contains(index)) { |
| 29 | +//保证线段的位置不相同 |
| 30 | +continue; |
| 31 | +} |
| 32 | +boards.add(index); |
| 33 | +} |
| 34 | + |
| 35 | +//计算每个红包的金额,将两个板子之间的钱加起来 |
| 36 | +Collections.sort(boards); |
| 37 | +List<Integer> list = new ArrayList<>(); |
| 38 | +for (int i = 0; i < boards.size() - 1; i++) { |
| 39 | +Integer e = boards.get(i + 1) - boards.get(i); |
| 40 | +list.add(e); |
| 41 | +} |
| 42 | +return list; |
| 43 | + |
| 44 | +} |
| 45 | + |
| 46 | +public static void main(String[] args) { |
| 47 | +List<Integer> accountList = getRandomMoney(10, 5); |
| 48 | +BigDecimal count = new BigDecimal(0); |
| 49 | +for (Integer amount : accountList) { |
| 50 | +//将抢到的金额再除以100进行还原 |
| 51 | +BigDecimal tmpcount = new BigDecimal(amount).divide(new BigDecimal(100)); |
| 52 | +count = count.add(tmpcount); |
| 53 | +System.out.println("抢到金额:" + tmpcount); |
| 54 | + |
| 55 | +} |
| 56 | +System.out.println("total = " + count); |
| 57 | +} |
| 58 | +} |
0 commit comments