Answer the question
In order to leave comments, you need to log in
How to choose sum terms?
There is a task to find the terms for a certain amount.
The terms are given by an array.
Can be used multiple times.
For example:
From the terms [1,2,6,10] you need to get the sum 15
The answer will be 10+2+2+1
There is an implementation for non-repeating terms, but this is not what you need:
function findSummand($sum, $parts, $depth = 0) {
static $args = array();
foreach ($parts as $k => $part)
{
if ($part == $sum)
{
$args[$depth] = $part;
return true;
}
if ($part < $sum)
{
$args[$depth] = $part;
if (findSummand($sum - $part, array_slice($parts, $k + 1), $depth + 1))
{
if ($depth == 0)
{
return $args;
}
return true;
}
}
}
if ($depth == 0) {
return 'Решение не найдено';
}
}
Answer the question
In order to leave comments, you need to log in
so what's so hard about it?
not only is the task not about a backpack, but a specific figure, you can also repeat it
by starting with decomposition into terms, and then iteration - enumeration of the missing delta and available elements
There is an implementation for non-repeating terms
Goodnight.
Try starting with the following function
function sumInit($array, $sum){
static $new = [];
static $result = null;
if(array_sum($new) == $sum){
$result = $new;
}
else{
$max = max($array);
$key_max = array_keys($array, max($array))[0];
if((array_sum($new) + $max) <= $sum){
$new[] = $max;
}
else if((array_sum($new) + $max) > $sum){
unset($array[$key_max]);
}
sumInit($array, $sum);
}
if($result != null){
return $result;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question