java实现抢红包算法

这里简单介绍一下二倍均值法。
我们为了保证每个人抢到的红包都均匀分布在合适的区间内,故引入二倍均值法。我们发现每个人抢到的红包金额并不是随机分布在0.01~金额总数的区间内,而是分布在[0.01,红包余额/剩余人数*2)的左闭右开区间内,即二倍均值法。由于金额单位最小至分,所以我们不能随机产生任意浮点数,必须事先将金额扩大100倍,最后再除以100以精确到小数点后两位。
以下是java代码实现:

package RedPocket;

import java.util.ArrayList;
import java.util.Iterator;
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("各人领取红包记录:");
		List list=red.snatch(redAmount=amount,restPeople=people);
		for(Iterator<Double> iter=list.iterator();iter.hasNext();)
			System.out.print(iter.next()+" ");
	}
}

运行结果如下所示:

各人领取红包记录:
5.29 12.81 2.58 5.31 3.24 7.86 9.14 12.36 15.8 0.35 14.81 3.86 15.06 18.98 13.86 14.65 9.23 13.08 9.96 4.63 4.66 2.48

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值