用java程序模拟抢红包。这里给出的随机抢红包算法比较简单。
例如,假设当前红包是5.2元,参与抢红包的人是6个人,那么第一个人抢到的金额m是一个在0~519的随机数(用分表示钱的金额)。
如果m是0,需要把m赋值成1(保证用户至少能够抢到1分钱);
如果m不是0,那么520-m是剩余的金额,要求剩余的金额必须保证其余5个人都至少能够抢到1分钱,否则m要减去多抢到的金额。
代码运行结果:
//RedEnvelope
public abstract class RedEnvelope {
public double remainMoney;//红包当前金额
public int remainPeople;//当前参与抢红包的人数
public double money;//当前用户抢到的金额
public abstract double giveMoney();//抽象方法,具体怎么抢红包由子类完成
}
//RandomRedEnvelope
import java.util.*;
public class RandomRedEnvelope extends RedEnvelope{
double minMoney;//可以抢到的最小金额
int integerRemainMoney;//红包中的钱用分表示
int randomMoney;//给用户抢的钱
Random random;
RandomRedEnvelope(double remainMoney,int remainPeople)
{
random=new Random();
minMoney=0.01;
this.remainMoney=remainMoney;
this.remainPeople=remainPeople;
integerRemainMoney=(int)(remainMoney*100);
if(integerRemainMoney<remainPeople*(int)(minMoney*100))
{
integerRemainMoney=remainPeople*(int)(minMoney*100);
this.remainMoney=(double)integerRemainMoney;
}
}
public double giveMoney()
{
if(remainPeople<=0)
{
return 0;
}
if(remainPeople==1)
{
money=remainMoney;
remainPeople--;
return money;
}
randomMoney=random.nextInt(integerRemainMoney);
if(randomMoney<(int)(minMoney*100))
{
randomMoney=(int)(minMoney*100);
}
int leftOtherPeopleMoney=integerRemainMoney-randomMoney;//当前用户留给其他人的金额
int otherPeopleNeedMoney=(remainPeople-1)*(int)(minMoney*100);//保证其他人能够继续抢的最少金额
if(leftOtherPeopleMoney<otherPeopleNeedMoney)
{
randomMoney-=(otherPeopleNeedMoney-leftOtherPeopleMoney);
}
integerRemainMoney-=randomMoney;
remainMoney=(double)(integerRemainMoney/100.0);//将剩余的钱转化为元
remainPeople--;
money=(double)(randomMoney/100.0);
return money;
}
}
public class example {
public static void main(String []args)
{
RedEnvelope redEnvelope=new RandomRedEnvelope(5.20,6);
System.out.printf("用以下循环输出%d个人抢%.2f元的随机红包:\n",redEnvelope.remainPeople,redEnvelope.remainMoney);
showProcess(redEnvelope);
}
public static void showProcess(RedEnvelope redEnvelope)
{
double sum=0;
while(redEnvelope.remainPeople>0)
{
double money=redEnvelope.giveMoney();
System.out.printf("%.2f\t",money);
sum+=money;
}
String s=String.format("%.2f", sum);
sum=Double.parseDouble(s);
System.out.printf("\n%.2f的红包被抢完", sum);
}
}
欢迎批评指正!