我们有一个整数假设28,现在我们需要一个平衡和的数组,如$ array =(10,10,8),当我们想要最大可能数为10时,如果最大可能数为5,则数组应该是像(5,5,5,5,5,3)。帮助我。
答案 0 :(得分:0)
Intresting.Try like
$var = 28;
$max_lmt = 10;
$i = 1;
while($i) {
$tmp = $var;
$var = $var - $max_lmt;
if($var > 0)
$arr[] = $max_lmt;
else {
$arr[] = $tmp;
$i = 0;
}
}
print_r($arr);
请参阅此OUTPUT
答案 1 :(得分:0)
function getBalancedSum($number, $max)
{
$array = array();
if ($number != 0
&& $max != 0
&& (($number > 0 && $max > 0)||($number < 0 && $max < 0)))
{
if ($number / $max > 1)
$array = array_fill(0, $number / $max, $max);
if ($number % $max)
$array[] = $number % $max;
}
return $array;
}
echo(json_encode(getBalancedSum(28, 10))); // [10,10,8]
echo(json_encode(getBalancedSum(28, 7))); // [7,7,7,7]
echo(json_encode(getBalancedSum(28, 30))); // [28]
echo(json_encode(getBalancedSum(0, 10))); // []
echo(json_encode(getBalancedSum(10, 0))); // []
echo(json_encode(getBalancedSum(28, -10))); // []
echo(json_encode(getBalancedSum(-28, -10))); // [-10,-10,-8]
Json仅用于输出。