每個人搶到的金額比較平均的算法
package com.example.demo.money; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class SnatchMoney { //二倍均值法 public static List<Integer> divideRedPackage(Integer totalAmount, Integer totalPeopleNum) { List<Integer> amountList = new ArrayList<Integer>(); //爲了使用random.nextInt(Integer)方法不得不先把紅包金額放大100倍,最後在main函數裏面再除以100 //這樣就可以保證每個人搶到的金額都可以精確到小數點後兩位 Integer restAmount = totalAmount * 100; 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; } //隨機金額法 private static List<Integer> divide(double money, int n) { //驗證參數合理校驗 //爲了使用random.nextInt(Integer)方法不得不先把紅包金額放大100倍,最後在main函數裏面再除以100 //這樣就可以保證每個人搶到的金額都可以精確到小數點後兩位 int fen = (int) (money * 100); if (fen < n || n < 1) { System.out.println("紅包個數必須大於0,並且最小紅包不少於1分"); } List<Integer> boards = new ArrayList<>(); boards.add(0); boards.add(fen); //紅包個數和板磚個數的關係 while (boards.size() <= n) { int index = new Random().nextInt(fen - 1) + 1; if (boards.contains(index)) { //保證板子的位置不相同- continue; } boards.add(index); } //計算每個紅包的金額,將兩個板子之間的錢加起來 Collections.sort(boards); List<Integer> list = new ArrayList<>(); for (int i = 0; i < boards.size() - 1; i++) { Integer e = boards.get(i + 1) - boards.get(i); list.add(e); } return list; } public static void main(String[] args) { // List<Integer> accountList = divideRedPackage(50, 1000); List<Integer> accountList = divideRedPackage(100, 10); BigDecimal count = new BigDecimal(0); for (Integer amount : accountList) { //將搶到的金額再除以100進行還原 BigDecimal tmpcount = new BigDecimal(amount).divide(new BigDecimal(100)); count = count.add(tmpcount); System.out.println("搶到金額:" + tmpcount); } System.out.println("total=" + count); } }