本文由我司收集整编,推荐下载,如有疑问,请与我司联系
java
实现微信红包分配算法
2017/03/25
0
红包算法分析有人认为,抢红包的额度是从
0.01
到剩余平均值
*N(N
是一个系数,决定最大的红包值
)
之间,比如一共发了
10
块钱,发了
10
个红
包:第一个人可以拿到
(0.01~1*N)
之间的一个红包值,当然为了确保所有人至少有
1
分钱拿,不能前几个人就把钱拿光了,因此需要有一个判断算法。举个例子,如
果每个人都拿了自己的最大值:
package
红包分配
;public
class
test
{
public
static
void
main(String[]
args){
float
num=10,N=1.9f;
int
people=10;
for(int
i=0;i
10;i++)
{
System.out.println(“the
number”+people+”can
get
“+num/people*N);
num=num-num/people*N;
people--;
}
System.out.println(“there
remain”+num);
}}
运行结果如下:
the
number10can
get
1.9the
number9can
get
1.71the
number8can
get
1.5176251the
number7can
get
1.3225019the
number6can
get
1.1241267the
number5can
get
0.9217838the number4can get 0.71438247the number3can get 0.5000677the
number2can
get 0.2750373the number1can get 0.027503723there remain-0.01302808
最终剩余的钱
数
为负数,不符合要求,因此说基数的选取是非常重要的。
设置金额的限额
private static final float MINMONEY = 0.01f;private static final float
MAXMONEY = 200f;
红包的最小额度是
0.01
元,最大额度是
200
元。
判断金额是否合法如果金额超过限额,就出错了
private
boolean
isRight(float
money,int
count){
double
avg
=
money/count;
if(avg
MINMONEY){ return false; } else if(avg MAXMONEY) { return false; } return true;}
随
机产生红包用随机方法产生一个在最大值和最小值之间的一个红包,并判断该红包
是否合法,是否在产生这个红包之后红包金额变成负数。另外,在这次产生红包值
较小时,下一次就产生一个大一点的红包。
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;//
如果最大值和最小值一样,就返回
mins
}
float
max
=
maxs