4

Suppose I have an array

a[3]={1,3,8}  

I want the output to be an array containing the numbers obtained by adding numbers from array a, as well as the elements of array a. i.e.,

b[0]=1
b[1]=3
b[2]=8
b[3]=4  //(1+3)
b[4]=9  //(1+8)
b[5]=11 //(3+8)
b[6]=12 //(1+3+8) 

How do I do this?

6
  • So you want to generate all possible subsets of a set of numbers and list their sum, right? Commented Jun 2, 2013 at 19:01
  • Similar to Fibonaccy but this has one more level? Commented Jun 2, 2013 at 19:02
  • Just to be clear, you want to compute the sum for each possible combination of elements from the array? Commented Jun 2, 2013 at 19:04
  • @OliCharlesworth that's what her example shows I'm not sure though :) Commented Jun 2, 2013 at 19:10
  • looks like finding subsets and the sum for each Commented Jun 2, 2013 at 19:12

2 Answers 2

3

So you want to generate all possible subsets of a set of numbers and list their sum.

First, you want to enumerate all the subsets. Since there are 2 ^ N subsets in a set containing N elements, you can simply do this by iterating through the natural numbers from 0 to 1 << (sizeof(arr) / sizeof(arr[0])) and treating the binary representation of the number in the following manner: if a particular bit is set at position k, then the kth element is in the currently generated subset, else it isn't.

Then, you should add all the selected elements together and store the result in the next slot of another array (sized 2 ^ N, obviously).

#define COUNT(a) (sizeof(a) / sizeof(a[0]))
#include <limits.h> // for CHAR_BIT

unsigned a[3] = { 1, 3, 8 };
unsigned sums[1 << COUNT(a)] = { 0 };

for (unsigned i = 0; i < COUNT(sums); i++) {
    for (unsigned j = 0; j < sizeof(i) * CHAR_BIT; j++) {
        if ((i >> j) & 1) {
            sums[i] += a[j];
        }
    }
}

for (unsigned i = 0; i < COUNT(sums); i++) {
    printf("%d\n", sums[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

I would do it like this:

b[0] = 0;  //This is not listed in the question, but should be included in the result IMHO.
for(long i = 0; i < elementsA; i++) {
    long preexistingElements = 1 << i;
    long curElement = a[i];
    for(long j = 0; j < preexistingElements; j++) {
        b[j + preexistingElements] = b[j] + curElement;
    }
}

This algorithm is linear in the size of the result array as each of its elements is computed with constant cost.

If you really must exclude the zero and want to malloc the result array, turn the algorithm around so that b is filled from the back with the zero element as the last element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.