这里简单介绍一下二倍均值法。
我们为了保证每个人抢到的红包都均匀分布在合适的区间内,故引入二倍均值法。我们发现每个人抢到的红包金额并不是随机分布在0.01~金额总数的区间内,而是分布在[0.01,红包余额/剩余人数*2)的左闭右开区间内,即二倍均值法。由于金额单位最小至分,所以我们不能随机产生任意浮点数,必须事先将金额扩大100倍,最后再除以100以精确到小数点后两位。
以下是java代码实现:
package RedPocket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RedPocket {
public static Integer amount;
public static Integer people;
public RedPocket(Integer amount,Integer people) {
this.amount=amount;
this.people=people;
}
public static List<Double> snatch(Integer redAmount,Integer restPeople){
redAmount=amount*100;
restPeople=people;
List<Integer> amountList=new ArrayList<Integer> ();
List<Double> list=new ArrayList<Double> ();
Random random=new Random();
for(int i=0;i<people-1;i++) {
int money=random.nextInt((redAmount/restPeople)*2-1)+1;
redAmount-=money;
restPeople--;
amountList.add(money);
}
amountList.add(redAmount);
for(int j=0;j<amountList.size();j++) {
list.add(amountList.get(j)/100.0);
}
return list;
}
public static void main(String[] args) {
Integer amount=200;
Integer people=22;
Integer redAmount=0;
Integer restPeople=0;
RedPocket red=new RedPocket(amount,people);
System.out.println("各人领取红包记录:");
System.out.println(red.snatch(redAmount=amount,restPeople=people));
}
}