Skip to content
Advertisement

All possible combinations of numbers with rounding error matching sum

I have encountered one problem that I struggle to solve. There is a group of numbers that should match some given sum and the function should output all possible combinations. The length of the input numbers differ, might be 3 or sometimes 20 numbers in the input array. Unfortunately, some numbers do have a rounding error and some do not have it, and we do not know which ones are accurate. Therefore, not always combination might be found for every sum, cause of it rounding error.

E.g. there are numbers 248, 512, 992, 240, 2134, 4214, 4211 and target sum is 3133.

I wanted to incorporate rounding error into the function that I found here:

JavaScript

And i wanted to do so by sort of extending the input array by 2*len(input_array) elements, where one would be an element-1 and second would be element+1.

Unfortunately, I do not know how to incorporate it into that algorithm and when i use loop to run the function multiple times with switching one element it will be super slow and create 3*length runs of this functions(actual number, actual number-1, actual numer+1). I dont think anyone would be able to help with this…

Advertisement

Answer

Ok, I guess you’re looking for the “best” sum, rather than “exact” one, that is, find a subset sum such as the distance abs(partial_sum, target) is minimal. You can employ this simple modification of the algorithm: on each step, compute the distance and declare it “best” if it is less than the best distance so far.

Here’s some working code (I also replaced recursion with a loop and a queue):

JavaScript

This prints

JavaScript

And here’s a modification to enumerate all such sums:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement