随机红包生成工具类
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class HBGenerateUtil {
public static void main(String[] args) {
generateHbList(BigDecimal.valueOf(300),BigDecimal.valueOf(90),BigDecimal.valueOf(3),BigDecimal.valueOf(1));
}
public static List<BigDecimal> generateHbList(BigDecimal totalAmt, BigDecimal totalNum, BigDecimal maxSingleAmt, BigDecimal minSingleAmt){
BigDecimal checkAmt = totalAmt;
BigDecimal checkNum = totalNum;
List<BigDecimal> hbList = new ArrayList<>();
int loop = totalNum.intValue();
for (int i = 1; i <= loop; i++) {
if(i != loop){
BigDecimal singleHb = singleHb(totalAmt,totalNum,maxSingleAmt,minSingleAmt);
totalAmt = totalAmt.subtract(singleHb);
totalNum = totalNum.subtract(BigDecimal.ONE);
hbList.add(singleHb);
}else{
BigDecimal singleHb = totalAmt;
hbList.add(singleHb);
}
}
Collections.shuffle(hbList);
checkHbList(hbList,checkAmt,checkNum);
return hbList;
}
private static void checkHbList(List<BigDecimal> hbList, BigDecimal valueOf, BigDecimal valueOf1) {
BigDecimal totalAmt = new BigDecimal(0);
for (int i = 0; i < hbList.size(); i++) {
BigDecimal singleHb = hbList.get(i);
totalAmt = totalAmt.add(singleHb);
}
if(valueOf.compareTo(totalAmt) == 0 && hbList.size() == valueOf1.intValue()){
System.out.println("效验成功!");
}else{
System.out.println("效验失败!");
}
}
public static BigDecimal singleHb(BigDecimal totalAmt,BigDecimal totalNum,BigDecimal maxSingleAmt,BigDecimal minSingleAmt){
double random = Math.random();
BigDecimal singleHb = (maxSingleAmt.subtract(minSingleAmt)).multiply(BigDecimal.valueOf(random)).add(minSingleAmt);
singleHb = singleHb.setScale(2,BigDecimal.ROUND_HALF_DOWN);
BigDecimal surplus = totalAmt.subtract(singleHb);
if(surplus.compareTo(
minSingleAmt.multiply(totalNum.subtract(BigDecimal.valueOf(1)))
) < 0){
return minSingleAmt;
}
if(surplus.compareTo(
maxSingleAmt.multiply(totalNum.subtract(BigDecimal.valueOf(1)))
) > 0){
BigDecimal newMinSingleAmt = totalAmt.subtract(maxSingleAmt.multiply(totalNum.subtract(BigDecimal.valueOf(1))));
singleHb = (maxSingleAmt.subtract(newMinSingleAmt)).multiply(BigDecimal.valueOf(random)).add(newMinSingleAmt);
singleHb = singleHb.setScale(2,BigDecimal.ROUND_HALF_DOWN);
}
return singleHb;
}
}