2

Having an array of integers (eg. 3, 4, 5), how can you find all combinations they can be added up to a given sum? (eg. 17)

For the example there would be four ways the three numbers can add up to 17:

  • 5 + 5 + 4 + 3
  • 5 + 4 + 4 + 4
  • 5 + 3 + 3 + 3 + 3
  • 4 + 4 + 3 + 3 + 3

How would you calculate this programmatically? Eg. using javascript.

hindmost
  • 6,828
  • 3
  • 23
  • 36
Deni
  • 119
  • 1
  • 1
  • 11
  • Something with `%` [modulo](http://stackoverflow.com/questions/8900652/what-does-do-in-javascript) perhaps? – loveNoHate Feb 11 '14 at 09:04
  • In your example incomplete combinations are allowed. E.g.: `5 + 4 + 4 + 4` (3 is missing). Is it right? – hindmost Feb 11 '14 at 09:13
  • @hindmost Yes, it's is right. Not all the numbers in the array need to be used. Only the first example uses every number :-) – Deni Feb 11 '14 at 13:11
  • Is there an array of three (or so) integers, and at most six (or so) summands? Or are the numbers much bigger than that? – Teepeemm Feb 11 '14 at 19:24
  • @Teepeemm The array with integers can be very big, but there will only be one sum. They will not get very big, but i believe that doesn't change the code? – Deni Feb 12 '14 at 07:04
  • @RobertDodier Thank you! I'll look that up, and get back :-) – Deni Feb 12 '14 at 07:05
  • @RobertDodier Will you please add an answer so that I can accept it :-) – Deni Feb 12 '14 at 21:29
  • @DSDeniso OK, I have done so. Glad to help. – Robert Dodier Feb 12 '14 at 22:46
  • 1
    The number of integer partitions grows really fast. If the numbers involved are small, this will make your coding easier because you won't need to use as many optimizations. – Teepeemm Feb 14 '14 at 21:57

2 Answers2

2

The general topic is called "integer partitions". Searching for that might turn up an algorithm you can use.

Robert Dodier
  • 14,751
  • 2
  • 25
  • 42
0

Here is a possible solution (i make no claim on its efficiency though):

  1. You create a data structure that holds a sum of numbers. (The value of that sum and all the numbers that compose it).
  2. You have an array A and a target sum TARGET.
  3. You sort the array A.
  4. You create a new array B, initialized from A with the data structure described above, where each element in B is the sum of the corresponding number in A.
  5. While(B has values)
    1. You add each of the numbers in A to the data structures in B (B will now have B.length*A.length elements)
    2. Each sum in B that is TARGET is a solution
    3. Each sum in B that is at least TARGET is removed from B

Note: If any combination of elements in A equals 0, then the program will never end (as expected). This implies that A must have all elements larger than 0

Tibos
  • 26,262
  • 4
  • 43
  • 59
  • Thanks for answering, but it looks quite complicated. I'll just use Robert's method :-) – Deni Feb 13 '14 at 07:52