基于BigDecimal、DecimalFormat、Random实现模拟红包算法
RedPacket 类
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Random;
public class RedPacket {
private String sumMoney;
private int count;
private Random r = new Random();
public RedPacket(String sumMoney, int count) {
super();
this.sumMoney = sumMoney;
this.count = count;
}
public ArrayList<BigDecimal> genPacket() throws RedPacketException{
ArrayList<BigDecimal> list = new ArrayList<>();
BigDecimal money = new BigDecimal("0.01");
//获取总金额的最小值
double minMoney = money.multiply(new BigDecimal(count)).doubleValue();
//将字符串类型的金额包装为BigDecimal
BigDecimal totalMoney = new BigDecimal(sumMoney);
//判断红包总金额是否大于红包最小值(判断总金额是否够分)
if(minMoney > totalMoney.doubleValue()){
throw new RedPacketException("每个红包不能少于0.01元");
}
if(minMoney == totalMoney.doubleValue()) {
//最低金额正好等于总金额(每人0.01)
for(int i = 0 ; i < count ; i++) {
list.add(new BigDecimal("0.01"));
}
return list;
}
double[] scales = randomScale();
//合计已经分配多少钱
BigDecimal sends = new BigDecimal("0");
for(int i = 0; i < scales.length-1 ; i++) {
//根据比例计算每个红包的应分得的金额
money = totalMoney.multiply(new BigDecimal(scales[i])).setScale(2, BigDecimal.ROUND_HALF_EVEN);
sends = sends.add(money);
list.add(money);
}
list.add(totalMoney.subtract(sends));
return list;
}
public double[] randomScale() {
//累计总随机值
double total = 0;
//临时数组存储每个红包的随机比例
double[] scales = new double[count];
for (int i = 0; i < count; i++) {
//随机获取一个从1-100的整数
int rint = r.nextInt(100)+1;
scales[i] = rint;
total += rint;
}
//计算比例
for (int i = 0; i < count; i++) {
scales[i] = scales[i] / total;
}
return scales;
}
public static void main(String[] args) throws RedPacketException {
ArrayList<BigDecimal> list = new RedPacket("10", 5).genPacket();
for (BigDecimal bd : list) {
System.out.print(bd + "元\t");
}
}
}
自定义异常 RedPacketException类
public class RedPacketException extends Exception{
public RedPacketException() {
// TODO Auto-generated constructor stub
}
public RedPacketException(String message) {
super(message);
}
}