D
D
Denis Shpuganich2017-11-18 16:45:26
PHP
Denis Shpuganich, 2017-11-18 16:45:26

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

3 answer(s)
D
Dimonchik, 2017-11-18
@dimonchik2013

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

B
Boris Korobkov, 2017-11-18
@BorisKorobkov

There is an implementation for non-repeating terms

And for repeating, you need to remove array_slice.
PS If you yourself wrote the specified code, then it would not be difficult to modify it. And if you take this code from a classmate, get an answer on the Toaster and pass the result for offset, then the mind will not increase from this.

D
Dmitry, 2017-11-19
@slo_nik

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 question

Ask a Question

731 491 924 answers to any question