Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Finding a combination of records that yield a given sum. 1

Status
Not open for further replies.

zakman

Programmer
Aug 15, 2001
49
0
0
US
Suppose that you have a collection of records in a table. Each record contains a column which has a non-zero integer amount in it. The amount can be positive or negative.

You are given a target amount. Your job is to retrieve all records in the table whose amount matches the target amount given. However, it could be that the sum of (2 or more) records yield the target amount. The result set needs to identify all records (single or combination) that match the target amount.

This is not a homework problem, even though I recall doing something like this in college... but that was long ago. This actually has a real-life use in trying to find an error in an accounting log.

Does anyone know of an efficient algorithm (well, preferably not N!) for this problem? Or is this one of those hopeless scenarios...

For example:

Record 1: 10
Record 2: -2
Record 3: 12
Record 4: 2
Record 5: 6
Record 6: 8
Record 7: 3
Record 8: 1

Target: 10

Result set: Record 1, (Records 2 + 3), (Records 4 + 6), (Records 2 + 4 + 5 + 7 + 8), etc.

Enjoy!

Kevin

 
It is not N!, all permutations...but 2^N, all combinations, because each record can be in or out. Even when you reach the given number, further negtives and positives can yield the same number. Were it positives only then it would still be all combinations but bound by the sum, that is, you quit searching a branch when equal or greater.





Forms/Controls Resizing/Tabbing
Compare Code
Generate Sort Class in VB
Check To MS)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top