Algorithm for selecting values ​​from the array closest to the target value?

I have an array of almost sorted values ​​with a length of 28 elements. I need to find a set of values ​​that are summed with the target value provided to the algorithm (or if the exact amount cannot be found, the closest amount is lower than the target value).

I currently have a simple algorithm that does this work, but does not always find a better match. It works under ideal conditions with a specific set of values, but I need a more reliable and accurate solution that can handle a wider set of data sets.

The algorithm should be written in C, not C ++, and is designed for the embedded system, so keep that in mind.

Here is my current algorithm for reference. It iterates starting from the highest value available. If the current value is less than the target amount, it adds the value to the output and subtracts it from the target amount. This is repeated until the amount is reached or ended. It displays a list sorted vertically.

//valuesOut will hold a bitmask of the values to be used (LSB representing array index 0, next bit index 1, etc)

void pickValues(long setTo, long* valuesOut)
{
    signed char i = 27;//last index in array
    long mask = 0x00000001;

    (*valuesOut) = 0x00000000;
    mask = mask<< i;//shift to ith bit
    while(i>=0 && setTo > 0)//while more values needed and available
    {
        if(VALUES_ARRAY[i] <= setTo)
        {
            (*valuesOut)|= mask;//set ith bit
            setTo = setTo - VALUES_ARRAY[i]._dword; //remove from remaining         }
        //decrement and iterate
        mask = mask >> 1;
        i--;
    }
}

A few more options:

  • Array of values It is likely to be almost sorted in ascending order, but this cannot be done, so suppose that sorting is not performed. In fact, there may be duplicate values.

  • , , . , , .

+1
3
+6

, , , NP-Complete.

, , , ( ), .

, e > 0 , O ((n * logt)/e) , (t - , n - ), , z 1/(1 + e) ​​ .

i.e y, sum z ,

z <= y <= (1+e)z

O ((n * logt)/e).

: http://www.cs.dartmouth.edu/~ac/Teach/CS105-Winter05/Notes/nanda-scribe-3.pdf

, .

+5

, (DP). - O (n * target) O (). , DP. , ( ) ( , ):
http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=dynProg

, , .

+1

Source: https://habr.com/ru/post/1694061/


All Articles