红包随机分

指定红包的总金额
指定红包的总个数
指定最小红包金额
指定最大红包金额

import com.common.utils.LogUtils;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class RedPacketUtil {

    /**
     * 把指定金额随机分成n份,每份不少于minCents且不超过maxCents
     * @param money    总额(单位:元)
     * @param n
     * @param minCents 最小金额(单位:分)
     * @param maxCents 最大金额(单位:分)
     * @return
     */
    public static List<Double> splitMoney(double money, int n, int minCents, int maxCents) {
        DecimalFormat df = threadLocal.get();

        if (money * 100 < minCents * n) {
            LogUtils.e("进入1");
            return null;
        }

        if (money * 100 > maxCents * n) {
            LogUtils.e("进入2");
            return null;
        }

        Random random = new Random();
        int[] arr = new int[n];

        int cents = (int) Math.round(money * 100 - minCents * n);
        if (cents > 0) {
            List<Integer> list = new ArrayList<Integer>();
            list.add(0);

            for (int i = 0; i < n - 1; i++) {
                list.add(random.nextInt(cents));
            }

            list.add(cents);
            Collections.sort(list);

            for (int i = 0; i < n; i++) {
                arr[i] = list.get(i + 1) - list.get(i) + minCents;
            }
        } else {
            for (int i = 0; i < n; i++) {
                arr[i] = minCents;
            }
        }

        limitMaxAmount(arr, maxCents);
        List<Double> resList = new ArrayList<Double>();

        for (Integer i : arr) {
            resList.add(i * 1.0 / 100);

            LogUtils.e("红包的内容是" + i * 1.0 / 100);
        }

        LogUtils.e("集合的长度是" + resList.size());

        return resList;
    }

    /**
     * 限制单个红包的最大金额
     *
     * @param arr
     * @param maxCents
     */
    private static void limitMaxAmount(int[] arr, int maxCents) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] <= maxCents) {
                continue;
            }

            while (arr[i] > maxCents) {
                for (int j = 0; j < arr.length; j++) {
                    if (arr[j] >= maxCents) {
                        continue;
                    }

                    arr[j] = arr[j] + 1;
                    arr[i] = arr[i] - 1;
                }
            }
        }
    }

    private static ThreadLocal<DecimalFormat> threadLocal = new ThreadLocal<DecimalFormat>() {

        protected DecimalFormat initialValue() {
            return new DecimalFormat("0.00");
        }

        ;

    };
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值