package com.suyun.test;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
@EnableScheduling
public class TestApplication {
public static void main(String[] args) {
BigDecimal totalMoney = new BigDecimal(10D);
BigDecimal coefficient = new BigDecimal(0.001D);
int totalRedPacket = 10;
int doubleLength = String.valueOf(coefficient.doubleValue()).length() - 2;
List<BigDecimal> redPacketMoneys = new ArrayList<>();
distributionRedPacket(totalMoney, coefficient, doubleLength, totalRedPacket, 1, redPacketMoneys);
BigDecimal totalRedPacketMoney = new BigDecimal("0");
for (int i = 0; i < redPacketMoneys.size(); i++) {
System.out.println("红包金额" + redPacketMoneys.get(i));
totalRedPacketMoney = totalRedPacketMoney.add(redPacketMoneys.get(i));
}
System.out.println("红包总金额" + totalRedPacketMoney);
}
/**
* 获取红包金额
*
* @param totalMoney 红包剩余总金额
* @param coefficient 红包金额系数
* @param doubleLength 小数点后面有多少位
* @param totalRedPacket 红包总个数
* @param getRedpacketNumber 当前为第几个红包
* @param redPacketMoneys 存储红包金额
* @return 当前红包金额
*/
public static BigDecimal distributionRedPacket(BigDecimal totalMoney, BigDecimal coefficient, int doubleLength, int totalRedPacket, int getRedpacketNumber, List<BigDecimal> redPacketMoneys) {
/**
* 当达到最后一个红包时,直接把剩下的金额给最后一个红包
*/
if (totalRedPacket < getRedpacketNumber) {
redPacketMoneys.add(totalMoney);
return totalMoney;
}
/**
* 获取当前红包的最大值
*/
BigDecimal money = totalMoney.subtract(coefficient.multiply(new BigDecimal(totalRedPacket - getRedpacketNumber)));
/**
* 随机或企业一个金额小于当前总金额减去还剩下多少个红包乘以最低红包金额的金额
*/
BigDecimal realMoney = new BigDecimal(Math.random() * money.doubleValue()).setScale(doubleLength, BigDecimal.ROUND_DOWN);
redPacketMoneys.add(realMoney);
getRedpacketNumber++;
/**
* 递归生成红包
*/
return distributionRedPacket(totalMoney.subtract(realMoney), coefficient, doubleLength, totalRedPacket, getRedpacketNumber, redPacketMoneys);
}
}
简单红包算法
于 2018-08-13 11:21:29 首次发布