I have a set of values below. What I need to find out is if any combination of these value's sums a certain value (46,134.77 in this case). What is the best way to figure this out? Of course it would take hours to do it manually.
And I would need to know what the combination is if it returned true. I could set this up in Excel VBA, or a C# app. Whatever would work. I just have no clue how to get there.
125.00 1,000.00 1,039.36 1,171.60 1,200.00 1,320.00 1,680.00 1,757.20 1,768.80 1,970.00 2,231.25 2,300.00 2,369.25 2,589.20 2,720.00 2,887.50 3,000.00 3,085.00 3,142.60 3,174.40 3,742.70 3,847.20 5,609.25 5,881.05 12,240.48 14,112.00 29,318.07 32,551.80
Read other answers/comments first. Here is a solution that could be used for a small set of data.
This is almost precisely a bounded knapsack problem, one of the most well-studied computation problems in history. Locally:
NP Complete means you should get ready to write a giant loop summing up every (or nearly every) combination of numbers.
I'd recommend not doing this by hand. Several hours is a gross underestimation. It would take your whole life. For example there are over 40 million combinations of 14 numbers when choosing from a pool of 28. (That's just the 14's).
What you are describing is a variant of the Knapsack problem. It's computationally Hard to solve effectively, but for a set this small it's feasible.
The exact combination of numbers for this specific input is:
I used the following Perl script to determine this solution:
Note that I've converted your decimal values to integers (by multiplying them all by 100), as floating-point comparisons are a minefield. (See What Every Computer Scientist Should Know About Floating-Point Arithmetic for details.)
Yes duskwuff is right. The ONLY combination that adds up to 46134.77 is this one:
125 1,000.00 1,320.00 2,231.25 3,085.00 3,174.40 5,881.05 29,318.07
It took 2 seconds to find out. I have used SumMatch Excel add-in.
As already mentioned in paislee's answer, this is a variation on the knapsack problem. In fact, this specific problem is called the subset sum problem, and like the knapsack problem, it is NP-complete.
The linked Wikipedia page shows how to solve the problem using dynamic programming, but note that due to its NP completeness it will always be slow/impossible to solve if you make your list of integers too large.
Here are some more related SO questions: