am un array cu urmatoarele numere:
Cod: Selectaţi tot
arr = [50, 100, 100, 100, 200, 200]
Cod: Selectaţi tot
number = 300
Multumesc!
Cod: Selectaţi tot
arr = [50, 100, 100, 100, 200, 200]
Cod: Selectaţi tot
number = 300
Cod: Selectaţi tot
/**
* gets all possible permutations of $array
* @param array $array
* @param array $permutations
* @return array
*/
function permutations($array, $permutations =[]) {
if( !empty($array) ) {
$result = [];
for( $i = count($array) - 1; $i >= 0; --$i ) {
$newItems = $array;
$newPerms = $permutations;
list($values) = array_splice($newItems, $i, 1);
array_unshift($newPerms, $values);
$result = array_merge($result, permutations($newItems, $newPerms));
}
}
else $result = array($permutations);
return $result;
}
/**
* Returns all possible key combinations of $array with a sum equal $maxSum
* @param array $array
* @param integer $maxSum
* @return array
*/
function combinations($array, $maxSum) {
// get all permutations of the array keys
$permutations = permutations(array_keys($array));
$combinations =[];
// loop all permutations
foreach( $permutations as $keys ) {
// create a container for each permutation to store calculation
$c_keys =[];
$c_sum =0;
// now loop through the permutation keys
foreach( $keys as $key ) {
// if the addition is still between or equal $maxSum
if( ($c_sum + $array[$key]) <= $maxSum ) {
// increment the sum and add key to result
$c_sum += $array[$key];
$c_keys[] = $key;
}
}
if($c_sum < $maxSum) continue;
// to be sure each combination only exists once in the result
// order the keys and use them as array index
sort($c_keys);
$combinations[join($c_keys)] = $c_keys;
// if($c_sum == $maxSum) break; //Uncoment to return just first result
}
// remove the created key-index from array when finished
return array_values($combinations);
}
$arr =[50, 100, 100, 100, 200, 200];
$sum = 400;
$keys = combinations($arr, $sum);
$first_re = $keys[0]; // keys of the first result
// Output array with results
echo '<pre>';
var_export($keys);