package com.aifocus.data.collection.service.pdd;
import java.util.ArrayList;
import java.util.List;
/**
* 微信随机分配红包算法
*
* @author leo-zeng
*
*/
public class RedEnvelopesDemo {
private static final float MINMONEY = 0.5f;
private static final float MAXMONEY = 20;
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 > 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;
}
private static final float TIMES = 2.1f;
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;
System.out.println(one);
}
return list;
}
public static void main(String[] args) {
RedEnvelopesDemo util = new RedEnvelopesDemo();
float totalMoney = 100;//总金额
int count = 20;//个数
float max = (float) (totalMoney * TIMES / count);
for (int i =1 ; i < count+1; i++){
float one =util.randomRedPacket(totalMoney, MINMONEY, max, count - i);
totalMoney -=one;
}
System.out.println(totalMoney);
// RedEnvelopesDemo util = new RedEnvelopesDemo();
List<Float> list = util.splitRedPackets(100, 20);
float a = 0;
for (Float aa : list) {
a=a+aa;
}
System.out.println(a);
}
}
微信红包
最新推荐文章于 2025-06-05 21:59:44 发布
5万+

被折叠的 条评论
为什么被折叠?



