I have an NSArray of NSNumbers with integer values such as [1,10,3]. I want to get the sum of all the possible subsets of these numbers. For example for 1,10 and 3 i would get:
1, 10, 3, 1+10=11, 1+3=4, 10+3=13, 1+10+3=14
there are 2^n possible combinations. I understand the math of it but im having difficulties putting this into code. so how can i put this into a method that would take the initial array of numbers and return an array with all the sums of the subsets? e.g -(NSArray *) getSums:(NSArray *)numbers;
I understand that the results grow exponentially but im going to be using it for small sets of numbers.
A simple recursive solution – probably somewhat inefficient, and it’s untested, but the general idea should be clear.
The key to the problem is to generate all the subsets of a given array. This can be done recursively by recognizing the following:
The set of subsets of an empty array is the empty array, and the sum of the elements in an empty array is zero. This is handled by the lines marked with
(1).If the array is not empty, then let the first element be X. Any subset either includes X or does not include it. Therefore, we will generate all the subsets of the array that does not include X (there’s the recursion, marked by
(2), calculate the sums of each subset, and then duplicate the array of sums and add X to each of the sums in the duplicated part (marked by(3)).If you have only a handful of items in the original array (say, less than 16), then you can also count from 0 to 2n-1 in a
forloop; each index will then correspond to a subset. The elements in theith subset can be determined by writingiin base 2 and selecting those items from the array which correspond to a digit 1 in the base 2 form. I believe this is even less efficient than my solution above.