红包算法

JAVA

public class SplitRedPacket {

	public static void main(String[] args) {
		LeftMoneyPackage leftMoneyPackage = new LeftMoneyPackage();
		leftMoneyPackage.remainMoney = 10;
		leftMoneyPackage.remainSize = 8;
		int i = 1;
		while (leftMoneyPackage.remainSize > 0) {
			double money = getRandomMoney(leftMoneyPackage);
			System.out.println(i + " : " + money);
			i++;
		}
	}

	public static double getRandomMoney(LeftMoneyPackage _leftMoneyPackage) {
		// remainSize 剩余的红包数量
		// remainMoney 剩余的钱
		if (_leftMoneyPackage.remainSize == 1) {
			_leftMoneyPackage.remainSize--;
			return (double) Math.round(_leftMoneyPackage.remainMoney * 100) / 100;
		}
		Random r = new Random();
		double min = 0.01; //最小金额
		double max = _leftMoneyPackage.remainMoney / _leftMoneyPackage.remainSize * 2;
		double money = r.nextDouble() * max;
		money = money <= min ? min : money;
		money = Math.floor(money * 100) / 100;
		_leftMoneyPackage.remainSize--;
		_leftMoneyPackage.remainMoney -= money;
		return money;
	}

}

class LeftMoneyPackage {
	public int remainSize;
	public double remainMoney;

	public static class BuildLeftMoneyPackage {
		
	}

}

PHP

$total=10;//红包总额
$num=8;// 分成8个红包,支持8人随机领取
$min=0.01;//每个人最少能收到0.01元

for ($i=1;$i<$num;$i++)
{
    $safe_total=($total-($num-$i)*$min)/($num-$i);//随机安全上限
    $money=mt_rand($min*100,$safe_total*100)/100;
    $total=$total-$money;
    echo '第'.$i.'个红包:'.$money.' 元,余额:'.$total.' 元 
';
}
echo '第'.$num.'个红包:'.$total.' 元,余额:0 元';

发表评论

电子邮件地址不会被公开。 必填项已用*标注