I have a list of numbers (source set), and someone took some or all of those numbers and summed them randomly to make a smaller set of numbers (target set). I have the source set and the target set, but I need to figure out what combination was used. Difficulty: I can't guarantee that all numbers in the source set were used to make the target set, and I can't guarantee that all numbers in the target set came from the source set. Here's a simple example:
- Source Set = 1,2,3,4,5
- Target Set = 3,8
- Result:
- ResultSet1: Sum([1,2])=3 Sum([3,5])=8 NotFound([]) NotUsed([4])
- ResultSet2: Sum([3])=3 Sum([1,2,5])=8 NotFound([]) NotUsed([4])
- ResultSet3: Sum([1,3,4])=8 NotFound([3]) NotUsed([2,5])
- Invalid answers:
- InvalidSet1: Sum([1,2])=3 Sum([3])=3 Sum([3,5])=8 NotFound([]) NotUsed:[4]
- Reason: each number from the source set may only be used once to create any target in a given result set
- InvalidSet1: Sum([1,2])=3 Sum([3])=3 Sum([3,5])=8 NotFound([]) NotUsed:[4]
I have found some great examples for deriving the above given a single target value, but I can't find a way to do it with an array of target values rather than a single value (and my coding skills are unfortunately not up to the task). The best start I have is this question, with the code below (note that I removed the s >= target check to accommodate my data):
def subset_sum(numbers, target, partial=[]):
s = sum(partial)
# check if the partial sum is equals to target
if s == target:
print "sum(%s)=%s" % (partial, target)
#if s >= target:
# return # if we reach the number why bother to continue
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i+1:]
subset_sum(remaining, target, partial + [n])
if __name__ == "__main__":
subset_sum([1,2,3,4,5],4)
This will output:
sum([1, 3])=4
sum([4])=4
I've made some valiant attempts at adding a second layer of recursion to support an array for the target, but I won't embarrass myself by putting the failures here.
I understand that the above code has limitations, and I'm open to solutions based on this code, or completely new code, and output in just about any logical format. Python is strongly preferred, but I would entertain just about anything (note: java gives me hives).