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.
void pickValues(long setTo, long* valuesOut)
{
signed char i = 27;
long mask = 0x00000001;
(*valuesOut) = 0x00000000;
mask = mask<< i;
while(i>=0 && setTo > 0)
{
if(VALUES_ARRAY[i] <= setTo)
{
(*valuesOut)|= mask;
setTo = setTo - VALUES_ARRAY[i]._dword;
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.
, , . , , .