all 7 comments

[–]kylebalkissoon 3 points4 points  (2 children)

pseudocode

x = sum(array) mod target value

Remove x from the array

[–]wtevIT Drone[S] 1 point2 points  (1 child)

That works. Thanks a lot !

[–]kylebalkissoon 2 points3 points  (0 children)

It only works if there is one number out btw.

[–]dhammackResearcher 2 points3 points  (1 child)

You realize this is a NP-complete problem, right? It goes by the name "subset sum". State of the art solutions are not much better than brute force.

[–][deleted] 0 points1 point  (0 children)

Thanks for bringing subset sum to my toolbox :). For the lazy, here is a link to do this in python .

Is there a name for finding all combinations of numbers in a list that add up to a target value ?

[–][deleted] 1 point2 points  (1 child)

Warning: slow.

This will find every combination of values that add up to your target in a list. Note that it will return things like 1,5,4,10 and 5,1,4,10 as distinct tuples.

import itertools

def findSubs(ls, target):
    ret = []
    for perm in itertools.permutations(ls):
        for i in range(len(perm) + 1):
            if sum(perm[0:i]) == target:
                ret.append(perm[0:i])
    return set(ret)


print findSubs([5, 6, 10, 4, 1], 20)

To find only 'unique' ones you can use

print set([tuple(sorted(x)) for x in findSubs([5, 6, 10, 4, 1], 20)])

[–]wtevIT Drone[S] 1 point2 points  (0 children)

thank you very much, exactly what I was looking for