验证中...
Languages: PHP
Categories: 算法分析
Latest update 2019-06-25 18:44
gistfile1.txt
Raw Copy
$total = 100; //待划分的数字
$div = 5; //分成的份数
$area = 10; //各份数间允许的最大差值
$average = round($total / $div);
$sum = 0;
$result = array_fill( 1, $div, 0 );
for( $i = 1; $i < $div; $i++ ){
//根据已产生的随机数情况,调整新随机数范围,以保证各份间差值在指定范围内
if( $sum > 0 ){
$max = 0;
$min = 0 - round( $area / 2 );
}elseif( $sum < 0 ){
$min = 0;
$max = round( $area / 2 );
}else{
$max = round( $area / 2 );
$min = 0 - round( $area / 2 );
}
//产生各份的份额
$random = rand( $min, $max );
$sum += $random;
$result[$i] = $average + $random;
}
//最后一份的份额由前面的结果决定,以保证各份的总和为指定值
$result[$div] = $average - $sum;
//结果呈现
echo '划分情况:';
foreach( $result as $temp ){
echo $temp.'<br/>';
}
echo '总和:', array_sum( $result );
exit;

Comment list( 0 )

You need to Sign in for post a comment

Help Search

183227_9af5e6a8_1826025 111910_4d91f001_1826025