JAVA 简单高效的金额随机分配 算法


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class SplitRedPacket {

    // 最小红包额度
    private static final int MINMONEY = 100;
    // 最大红包额度
    private static final int MAXMONEY = 900;


    /**
     * @Description: 随机拆分红包
     * @Author: liumeng
     * @Date: 2019/2/27
     * @Param: [money, count]
     * @Return: java.util.List<java.lang.Integer>
     **/
    public static List<Integer> splitRedPackets(int money, int count) {

        if(money < count*MINMONEY || money > count* MAXMONEY){
            System.out.println("不可拆分");
            return null;
        }
        // 先预留出 count 份 minS , 其余的做随机
        int moreMoney = money-count*MINMONEY;
        List<Integer> list = new ArrayList<Integer>();
        for(int i=0; i<count; i++){
            int one = random(moreMoney,count-i, MINMONEY, MAXMONEY);
            list.add(one+MINMONEY);
            moreMoney = moreMoney-one;
        }
        Collections.shuffle(list);
        return list;
    }


    /**
     * @Description: 随机红包数额(加上minS 为实际金额)
     * @Author: liumeng
     * @Date: 2019/2/27
     * @Param: [money, count]
     * @Return: java.util.List<java.lang.Integer>
     **/
    private static int random(int money,  int count, int minS, int maxS) {
        // 红包数量为1,直接返回金额
        if (count == 1) {
            return money;
        }
        // 每次限定随机数值
        // 首先判断实际最小值
        int realMinS = money-(maxS-minS)*(count-1);
        int realRange ;
        // 如果存在实际最小值,则在实际最小值realMinS 和 maxS-minS 之间 random 数值
        if(realMinS > 0){
            realRange = maxS-minS-realMinS + 1;
        }
        //  如果不存在实际最小值(也就是说数值可以是minS)
        else{
            if(money > maxS-minS){
                realMinS = 0;
                realRange = maxS-minS + 1;
            }else{
                realMinS = 0;
                realRange = money + 1;
            }
        }

        return  new Random().nextInt(realRange) + realMinS;


    }



    public static void main(String[] args) {
        int money = 2500 ;
        int count = 6;
        for(int i=0; i<7; i++) {
            List list = splitRedPackets(money, count);
            if (list != null) {
                System.out.println("随机拆分" + money + "拆分" + count + "份:" + list);
            }
        }
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值