一天一个小算法(01 红包算法)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29923439/article/details/84024708

/**
 * 红包算法
 * @author admin
 *
 */
public class RedPacket {
    
    //最新金额
    private static final int MIN_MONEY=1;
    
    //最大金额
    private static final int MAX_MONEY=20000;
    
    //最大的红包是平均值的 TIMES 倍,防止某一次分配红包较大
    private static final float SINGLE_MAXIMUM=2.1F;
    
    //重试次数
    private static  int reTry=0;
    
    /**
     * 红包集合
     * @param money 红包金额
     * @param count 红包数量
     * @return
     */
    public static List<Integer> redPackets(int money,int count){
        String result=checkMoney(money,count);
        if(StringUtils.isBlank(result))return null;
        List<Integer>redPackets=new ArrayList<Integer>();
        //分配红包
        for (int i = count; i > 0; i--) {
            //最大红包
            int max_packet=(int) ((int)(money/i) *SINGLE_MAXIMUM);
            //随机红包最大值
            int packet=getRedPacket(money,i,max_packet);
            money-=packet;
            redPackets.add(packet);
        }
        return redPackets;
    }

    private static int getRedPacket(int money, int count,int max_packet) {
        if(count==1) {
            return money;
        }
        if (MIN_MONEY == max_packet) {
            return MIN_MONEY;
        }
        if(max_packet>money)max_packet=money;
        int packet=(int) (Math.random()*(max_packet-MIN_MONEY)+MIN_MONEY);
        int lastMoney = money - packet;
        int avg=lastMoney/count;
        if(avg>max_packet ||avg<MIN_MONEY) {
            reTry++;
            System.err.println("reTry:"+reTry);
            getRedPacket(money, count, max_packet);
        }
        return packet;
    }

    private static String checkMoney(int money,int count) {
        if(money>MAX_MONEY) {
            System.err.println("红包超过最大金额限制,mongey:"+money);
            return null;
        }
        if(money<MIN_MONEY) {
            System.err.println("红包超过最小金额限制,mongey:"+money);
            return null;
        }
        if(count<0) {
            System.err.println("红包个数限制,count:"+count);
            return null;
        }
        return "ok";
    }
    
    public static void main(String[] args) {
        List<Integer> redPackets=redPackets(2000,10) ;
        System.err.println(JSONObject.toJSONString(redPackets));
        int count=0;
        for (int redPacket : redPackets) {
            count=count+redPacket;
        }
        System.err.println(count);

    }

}
 

猜你喜欢

转载自blog.csdn.net/qq_29923439/article/details/84024708