最低为1元的红包算法

package com.util;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RedBagUtil {
 public static void main(String[] args) {
  List<String> redBagList = RedBagToRandomForList(100.85,100,0.01);
  for(int i=0; i<redBagList.size(); i++){
   System.out.println("第"+(i+1)+" 个红包:"+redBagList.get(i));
  }
 }
 public static List<String> RedBagToRandomForList(double total, int count, double min) {
  List<String> list = new ArrayList<String>();
  List<String> redBagList = RedBagUntil(total,count,min);
  int[] sub = new int[redBagList.size()];
  if(redBagList!=null && redBagList.size()>0){
   for(int i=0; i<redBagList.size(); i++){
    sub[i]=i;
   }
   if(sub!=null && sub.length>0){
    int index,result;
    for(int j = 0 ;j < sub.length ;j++){
     index = new Random().nextInt(count);
     result = sub[j];
     sub[j] = sub[index];
     sub[index] = result;
    }
    for(int j : sub){
     double money = Double.parseDouble(redBagList.get(j))+1;
     String moneyStr = (String.format("%1$.2f", money));
     list.add(moneyStr);
    }
   }
  }else{
   System.out.println("程序报错");
  }
  return list;
 }
 
 /**
     * total 红包总额,count 红包个数,min 红包的最小金额;
     * 开始:
  * 要确保每个人(count-1)都有一个最小值的红包==》真正可以分的金额中获取平均数<(count-1)人>
  * ==》(count-1)人在每次剩下的金额中的每个人实际可用用到的 随机金额(随机要用到伪随机数)==》最后一个人就是剩下的金额
  * 要防止每次第一个红包都不会是最多的(毕竟伪随机数取不到1)所以放入集合中再随机排序一次;
  * 金额要大于等于 个数*最小金额,最小金额和红包个数都不能为0(这个到时候会在页面上处理)
  * */
 public static List<String> RedBagUntil(double total, int count, double min){
  List<String> list = new ArrayList<String>();
  int sumry = count * 1;
  total = total - sumry;
  total = new BigDecimal(total).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
  for(int i=1;i<count;i++){
   double money = 0d;
   if(total!=0){
    double actualTotal = total/(count-i);
    money = Math.random()*actualTotal;//随机数+原有的最小值
    //取小数点后两位
    money = new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); 
    total = total-money;
    total = new BigDecimal(total).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
//    System.out.println("第"+i+"个红包--"+(money)+"还剩--"+total);
   }else{
    money = 0d;
//    System.out.println("第"+i+"个红包--"+(money)+"还剩--"+total);
   }
   list.add(String.format("%1$.2f", money));
  }
  list.add(String.format("%1$.2f", total));
//  System.out.println("第"+count+"个红包--"+(total)+"还剩--"+total);
  return list;
 }
}

你可能感兴趣的:(最低为1元的红包算法)