微信分发红包算法

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

开发步骤:

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));
    }
}

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

转载于:https://www.cnblogs.com/huojg-21442/p/7552951.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值