微信红包算法
每个人获得的红包金额都在0.01-剩余红包总金额/剩余红包个数*2
范围内.那么如果先抢红包的人运气好,那么后续可能会出现后面的人不够0.01
的情况,就要保证这种情况不会出现.那么是否这样就会导致不公平呢?其实不然,先抢的人如果运气差,那么后面的人获得的金额均值会变大.
下面是我的实现(如有不足请指出)
- 最后一个人可以直接获得红包剩下所有金额
- 如果某个人获得的钱会使得剩下的人不够
0.01
,那么就要使其可能获得的最大值为剩下所有钱- 剩下每人
0.01元的钱
- 每人获得钱都要取两位小数
public class HongBao {
public static void main(String[] args) {
LeftHongBao leftHongBao = new LeftHongBao(7.32,5);
for (int i = 0; i < 5; i++) {
double res = getHongBao(leftHongBao);
System.out.println(res);
}
}
public static double getHongBao(LeftHongBao leftHongBao){
Random r = new Random();
double money = leftHongBao.getLeftMoney();
int count = leftHongBao.getLeftCount();
if(count == 1){
leftHongBao.setLeftMoney(0d);
leftHongBao.setLeftCount(0);
money = Double.parseDouble(String.format("%.2f",money));
return money;
}
double max = money/count*2;
//r.nextDouble返回[0,1)之间的随机数
double tar = r.nextDouble()*max;
tar = Double.parseDouble(String.format("%.2f",tar));
if((count - 1)*0.01 > money - tar){
max = money - (count - 1)*0.01;
tar = r.nextDouble()*max;
tar = Double.parseDouble(String.format("%.2f",tar));
}
if(tar < 0.01){
tar = 0.01;
}
leftHongBao.setLeftMoney(money - tar);
leftHongBao.setLeftCount(count - 1);
return tar;
}
}
class LeftHongBao{
public LeftHongBao(){
}
public LeftHongBao(double leftMoney, int leftCount) {
this.leftMoney = leftMoney;
this.leftCount = leftCount;
}
private double leftMoney;
private int leftCount;
public double getLeftMoney() {
return leftMoney;
}
public void setLeftMoney(double leftMoney) {
this.leftMoney = leftMoney;
}
public int getLeftCount() {
return leftCount;
}
public void setLeftCount(int leftCount) {
this.leftCount = leftCount;
}
}
输出
0.56
2.4
2.08
0.15
2.13