随机红包算法java代码 随机红包的算法( 三 )


//'/'部分
if($x1 != $x2$x = $x1$x = $x2)
{
、 $y = 1.0 * ($x - $x1) / ($x2 - $x1) * ($y2 - $y1) + $y1; return number_format($y, 2, '.', '');
}
//'\'形状
if($x2 != $x3$x = $x2$x = $x3)
{
$y = 1.0 * ($x - $x2) / ($x3 - $x2) * ($y3 - $y2) + $y2; return number_format($y, 2, '.', '');
}
return 0;
}
/**
* 格式化修红包数据
*
* @param mixed $leftMoney
* @param array $data
* @access public
* @return void
*/
private function format($leftMoney,array $data)
{
//不能发随机红包
if(false == $this-isCanBuilder())
{
return array($leftMoney,$data);
}
//红包剩余是0
if(0 == $leftMoney) //?需修数据
return array($leftMoney,$data);
}
//数组为空
if(count($data)1)
{
return array($leftMoney,$data);
}
//如果是可以有剩余,并且$leftMoney0
if('Can_Left' == $this-formatType
$leftMoney0)
{
return array($leftMoney,$data);
}
// 如果还有余钱,则尝试加到?红包? , 如果加不进去 , 则尝试下?个 。while($leftMoney0)
{
$found = 0;
foreach($data as $key = $val)
{
//减少循环优化
if($leftMoney = 0)
{
break;
}
//预判
$afterLeftMoney = (double)$leftMoney - 0.01;
$afterVal = (double)$val + 0.01;
if( $afterLeftMoney = 0$afterVal = $this-maxMoney)
{
$found = 1;
$data[$key] = number_format($afterVal,2,'.','');
$leftMoney = $afterLeftMoney;
//精度
}
}
//如果没有可以加的红包,需要结束,否则死循环
//也就是会出现每个红包不分钱的情况,?如红包都已经最?值 。这时必须在分的时候给予标志,防?死循环 。if($found == 0)
{
break;
}
}
//如果$leftMoney0,说明?成的红包超过预算了 , 需要减少部分红包?额
while($leftMoney0)
{
$found = 0;
foreach($data as $key = $val)
{
if($leftMoney = 0)
{
break;
}
//预判
$afterLeftMoney = (double)$leftMoney + 0.01;
$afterVal = (double)$val - 0.01;
if( $afterLeftMoney = 0$afterVal = $this-minMoney)
{
$found = 1;
$data[$key] = number_format($afterVal,2,'.','');
$leftMoney = $afterLeftMoney;
$leftMoney = number_format($leftMoney,2,'.','');
}
}
//如果?个减少的红包都没有的话,需要结束,否则死循环
if($found == 0)
{
}
}
return array($leftMoney,$data);
}
}
//维护策略的环境类
class RedPackageBuilder
{
// 实例
protected static $_instance = null;
/**
* Singleton instance(获取??的实例)
*
* @return MemcacheOperate
*/
public static function getInstance()
{
if (null === self::$_instance)
{
self::$_instance = new self();
}
return self::$_instance;
}
/**
* 获取策略【使?反射】
*
* @param string $type 类型
* @return void
*/
public function getBuilderStrategy($type) {
$class = $type.'PackageStrategy';
if(class_exists($class))
return new $class();
}
else
{
throw new Exception("{$class} 类不存在!");
}
}
public function getRedPackageByDTO(OptionDTO $optionDTO)
{
//获取策略
$builderStrategy = $this-getBuilderStrategy($optionDTO-builderStrategy); //设置参数
$builderStrategy-setOption($optionDTO);
return $builderStrategy-create();
}
}
class Client
{
public static function main($argv)
{
//固定红包
$dto = OptionDTO::create(1000,10,100,100,'Equal');

推荐阅读