一天一個小演算法(01 紅包演算法)
/**
* 紅包演算法
* @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);
}
}