首頁 > 後端開發 > php教程 > 已知n个数的和是32898,求每一个加数,求完美版

已知n个数的和是32898,求每一个加数,求完美版

WBOY
發布: 2016-06-23 13:27:55
原創
1111 人瀏覽過

原帖已经结贴。只是获得的结果并不完美,总是最大数999重复太多,显得不够随机,有点假。
http://bbs.csdn.net/topics/391814341

$r = foo(32898, 53);echo array_sum($r), PHP_EOL; //验证总和print_r(array_count_values($r)); //查看分布function foo($num, $k, $min=1, $max=999) {  $res = array_fill(0, $k, 1);  do {    for($i=0; $i<$k; $i++) {      $sum = array_sum($res);      $t = rand(0, $max - $min);      if($res[$i] + $t > $max) $t = $max - $res[$i];      if($sum + $t > $num) $t = $num - $sum;      $res[$i] += $t;    }  }while($num > $sum);  return $res;}
登入後複製


请修复这个问题,谢谢。


回复讨论(解决方案)

$t = rand(0, $max - $min);
改为
$t = rand(0, $max - $res[$i]);

这样的分布应该很好了

Array(    [886] => 1    [760] => 1    [470] => 1    [875] => 1    [591] => 1    [499] => 1    [257] => 1    [954] => 1    [264] => 1    [615] => 1    [770] => 1    [644] => 1    [971] => 1    [979] => 1    [259] => 1    [906] => 1    [830] => 1    [537] => 1    [595] => 1    [531] => 1    [588] => 1    [748] => 1    [767] => 1    [844] => 1    [931] => 1    [835] => 1    [986] => 1    [976] => 1    [89] => 1    [157] => 1    [408] => 1    [582] => 1    [593] => 1    [876] => 1    [710] => 1    [130] => 1    [554] => 1    [774] => 1    [386] => 1    [339] => 1    [686] => 1    [194] => 1    [903] => 1    [304] => 1    [207] => 1    [978] => 1    [232] => 1    [618] => 1    [834] => 1    [472] => 1    [839] => 1    [377] => 1    [788] => 1)
登入後複製

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板