Присвойте равное или меньшее с нулевым целевым числом против другого массива в переполнении стека

кандидат 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]);

0

Решение

Попробуйте следующее, это будет извлечь случайное нет между 1 & cardiate_array [$ я]. После этого он уменьшит число целевого распределения на это случайное число. Продолжится, пока 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;
}
}
}
}
}
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector