在php中为另一个数组分配等于或小于0的目标数

时间:2017-11-01 06:46:06

标签: php arrays random assign

候选人array= {10, 1, 2, 7, 6, 1, 5};

目标Number = 15

可以将随机目标number=15分配到候选数组吗?

可能的输出可能是:

对候选数组分配等于或小于零的目标数,如:

 $output =array([10] => [2],[1]=>[0], [2]=>[2], [7]=>[5], [6]=>[3],  [1]=>[1], [5]=>[2]);

1 个答案:

答案 0 :(得分:1)

尝试以下操作,这将在1&之间提取随机数。 cardiate_array [$ i]中。之后,它将通过该随机数减少目标分布数。将继续,直到targetNumber被完全消耗。

$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;
                }
            }
        }
    }
}