欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

再问红包算法,之前的有bug,@JXYCYFLM,@

程序员文章站 2022-04-13 09:48:32
...
http://bbs.csdn.net/topics/391001579
之前的帖子在此。


两位的算法都是有问题的。

版主给出的修订版,每当红包数量是单数的时候就不对了。加起来不等于总数。


恳请两位大侠帮忙修正。


回复讨论(解决方案)

$r = distribute(100, 31);echo array_sum($r), PHP_EOL;print_r($r);function distribute($total, $num) {  $avg = $total / $num;  $r = array_fill(0, $num, round($avg, 2));   for($i=0; $i  
$r = distribute(100, 31);echo array_sum($r), PHP_EOL;print_r($r);function distribute($total, $num) {  $avg = round($total / $num, 2);  $r = array_fill(0, $num, $avg);   for($i=0; $i  

100Array(    [0] => 1.03    [1] => 5.43    [2] => 0.09    [3] => 6.37    [4] => 0.65    [5] => 5.81    [6] => 2.24    [7] => 4.22    [8] => 1.66    [9] => 4.8    [10] => 2.53    [11] => 3.93    [12] => 0.14    [13] => 6.32    [14] => 2.85    [15] => 3.61    [16] => 0.72    [17] => 5.74    [18] => 0.34    [19] => 6.12    [20] => 1.31    [21] => 5.15    [22] => 1.1    [23] => 5.36    [24] => 0.31    [25] => 6.15    [26] => 1.68    [27] => 4.78    [28] => 0.66    [29] => 5.8    [30] => 3.1)

function distribute($total,$num){	return _distribute($total,$num,$total/$num/2,0);}function _ceil($i){	return ((int)($i*100))/100;}function _distribute($total,$num,$pj,$last_c){	if($num==0){		return array();	}	else if($num==1){		return array($total);	}	else {				$cz=_ceil(mt_rand(-$pj*100,$pj*100)/100);		$n=_ceil($pj+$cz+$last_c);		$res[]=$n;		if($num-1>=0)		$res=array_merge($res,_distribute($total-$n,$num-1,$pj,$pj-$cz));		return $res;	}}$ary=distribute(50,12);print_r(array_sum($ary));print_r($ary);

奉上娱乐型红包代码

function fn($total, $part, $min = 0.01) {	$res = array_fill(0, $part, $min);	$total -= $part * $min;	for($i=0; $i