将一个数Number按照拆分成N个在(min, max)范围内的数
方法一
基本思想:循环1 ~ N,每次循环,都计算随机范围(min , max),判断是否可以生成N个满足要求的数
<?php
/**
* 将一个数按照拆分成N个在(min, max)范围内的数
* @param [type] $number 待拆分的数
* @param [type] $count 拆分的数字的个数
* @param [type] $min 拆分的数字的最小值
* @param [type] $max 拆分的数字的最大值
* @return [type] 返回list
*/
function splitOneNumberToMultiNumber($number, $count, $min, $max){
$list = [];
$total_last = $number;
for ($i=1; $i <= $count ; $i++) {
$_min = $total_last - ($count - $i) * $max;
$_max = $total_last - ($count - $i) * $min;
$min = $_min >= $min ? $_min: $min;
$max = $_max >= $max ? $max: $_max;
if($i == $count){
$list[$i] = $total_last;
} else {
$list[$i] = rand($min , $max);
}
$total_last = $total_last - $list[$i];
}
return $list;
}
$list = splitOneNumberToMultiNumberPre(1000, 5 ,100, 300);
echo implode(',', $list);
方法二
基本思想:用最小值进行预处理,生成预处理数组,长度为N,每个key对应的值为最小值min,重置(min,max),然后循环:1 ~ N,每次循环都需重置(min,max), 终止条件为:i == N,或者total_last为0;
<?php
/**
* 将一个数按照拆分成N个在(min, max)范围内的数
* @param [type] $number 待拆分的数
* @param [type] $count 拆分的数字的个数
* @param [type] $min 拆分的数字的最小值
* @param [type] $max 拆分的数字的最大值
* @return [type] 返回[]
*/
function splitOneNumberToMultiNumberPre($number, $count, $min, $max){
$list = [];
for ($i=1; $i <= $count; $i++) {
$list[$i] = $min;
}
$total_last = $number - $count * $min;
$max = $max - $min;
$min = 0;
for ($i=1; $i <= $count ; $i++) {
$_min = $total_last - ($count - $i) * $max;
$_max = $total_last - ($count - $i) * $min;
$min = $_min >= $min ? $_min: $min;
$max = $_max >= $max ? $max: $_max;
if($i == $count){
$rand = $total_last;
$list[$i] += $rand;
} else {
$rand = rand($min , $max);
$list[$i] += $rand;
}
$total_last = $total_last - $rand;
if($total_last == 0){
break;
}
}
return $list;
}
$list = splitOneNumberToMultiNumberPre(1000, 5 ,100, 300);
echo implode(',', $list);
NOTE
将一个数Number按照拆分成N个数:没有限制的时候,自己生成初始的最大值:max(Number - (N - 1) * 1),而最小值min肯定为1,剩下的处理方式同上