在php中为另一个数组分配等于或小于0的目标数
Candidate array= {10, 1, 2, 7, 6, 1, 5};
Target Number = 15
Can distribute random target number=15
into candidate array?
Possible output of could be:
Assign equal or less with zero target number against candidate array like is:
$output =array([10] => [2],[1]=>[0], [2]=>[2], [7]=>[5], [6]=>[3], [1]=>[1], [5]=>[2]);
Candidate 目标 可以将随机目标 可能的输出可能是: p>
对候选数组分配等于或小于零的目标数,如: p> \ n
array = {10,1,2,7,6,1,5}; code> p>
Number = 15 code> p>
number = 15 code>分配到 候选阵列? p>
$ output = array([10] => [2],[1] => [0],[2] => [2],[7] => [5],[6] => [3],[1] => [1],[5] => [2]);
code> pre>
div >
Try the following, This will extract a random no between 1 & cardiate_array[$i]. After that it will reduce the target distribution number by that random number. Will continue until targetNumber is fully consumed.
$candidate_array = array(10, 1, 2, 7, 6, 0, 5);
$i = 0;
$newArray = [] ;
$number = 15;
//Precaution
$sum = array_sum($candidate_array) ;
if( $number > $sum ) {
//we can only distribute only $sum amount maximum.
$number = $sum ;
}
//repeat until fully consumed.
while( $number > 0 ) {
foreach( $candidate_array as $i => $val ) {
if( ! isset($newArray[$i]) ) {
$newArray[$i] = 0 ;
}
if( $number > 0 ) {
if( $val > 0 ) {
if( $newArray[$i] < $candidate_array[$i] ) {
//Find the maximum can be applied
$max = $candidate_array[$i] - $newArray[$i] ;
//Second iteration ? limit max value. This can be improved more.
if( $max > $number ) {
$max = $number ;
}
$rnd = rand(1,$max ) ;
//EDIT: A rand results in integer value, which again check with max (float) value. There is possibility of extra 0.5 added in result array which will be solved here.
if( $rnd > $max ) {
$rnd = $max ;
}
$newArray[$i] += $rnd ;
//Consume the number assigned.
$number -= $rnd ;
continue;
}
}
}
}
}