微信分发红包算法

大家想必都知道微信的红包哄抢吧,那么微信的红包如何设计的呢。今天让我们把这个小功能。研究一下。废话不多说,直接看代码

开发步骤:

1.设置金额的上下限

2,判断金额的是否在上下限的范围内。

3,随机产生红包金额

4,实现红包的分配,为了避免一个红包占用大量的金额,设定非最后一个红包的 最大金额,可以设置平均值的N陪。

  

 

package com.huojg.test;

import java.util.ArrayList;
import java.util.List;

/**
 * 红包算法分析
 * 
 * 1.设置金额的上下限 2.判断金额是否合法 3.随机产生红包
 * 
 * 
 */
public class RedPacketUtil {
    //1.设置金额的上下限   最少0.01,最多200
    private static final float MINMONEY = 0.01f;
    private static final float MAXMONEY = 200f;
    private static final double TIMES = 2.1;
    /**
     * 4.实现红包分配,为了避免一个红包占用大量的金额,设定非最后一个红包的 最大金额,可以设置平均值的N陪,
     * 
     * */
    public List<Float> splitRedPackets(float money, int count) {
        if (!isRight(money, count)) {
            return null;
        }
        List<Float> list = new ArrayList<Float>();
        float max = (float) (money * TIMES / count);

        max = max > MAXMONEY ? MAXMONEY : max;
        for (int i = 0; i < count; i++) {
            float one = randomRedPacket(money, MINMONEY, max, count - i);
            list.add(one);
            money -= one;
        }
        return list;
    }
/**
 * 3.随机产生红包
 * 
 * */
    private float randomRedPacket(float money, float mins, float maxs, int count) {
        if (count == 1) {
            return (float) (Math.round(money * 100)) / 100;
        }
        if (mins == maxs) {
            return mins;
        }
        float max = maxs > money ? money : maxs;
        float one = ((float) Math.random() * (max - mins) + mins);
        one = (float) (Math.round(one * 100)) / 100;
        float moneyOther = money - one;
        if (isRight(moneyOther, count - 1)) {
            return one;
        } else {

            float avg = moneyOther / (count - 1);
            if (avg < MINMONEY) {
                return randomRedPacket(money, mins, one, count);
            } else if (avg > MAXMONEY) {
                return randomRedPacket(money, one, maxs, count);
            }
        }
        return one;
    }
//2.判断金额是否合法  如果超过了最大值与最小值,错误
    private boolean isRight(float money, int count) {
        double avg = money / count;
        if (avg < MINMONEY) {
            return false;
        } else if (avg > MAXMONEY) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {

        RedPacketUtil util = new RedPacketUtil();
        System.out.println(util.splitRedPackets(200, 100));
    }
}

代码清晰明了。大家都可以看明白。

posted @ 2017-09-19 17:29  技术专家  阅读(852)  评论(0编辑  收藏  举报