Last active
August 29, 2015 14:12
-
-
Save saikatkumardey/1139acffea7bf104ef69 to your computer and use it in GitHub Desktop.
Generate all possible sub-set sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
//Given an array, generate all possible sum | |
int main(void) | |
{ | |
int array[]= {1,2,3}; | |
int N= sizeof(array)/sizeof(int); | |
for(int mask=0; mask < 1<<N; mask++) //generate numbers from 0 to 2^N-1. | |
//Number of subsets for a N-length set = 2^N (including the empty set) | |
{ | |
int sum=0; | |
//Suppose that mask=6, in binary: 6 = 110 | |
//The for-loop below works like this: | |
//check 0th bit, it is 0 so, no action, sum=0 | |
//check 1st bit, it is 1, so add array[1] to sum | |
//check 2nd bit, it is 1, so add array[2] to sum | |
//ultimately, sum = 0 + array[1] + array[2] | |
//similarly, for 7=111 | |
//all bits are set | |
//so, sum= array[0] + array[1] + array[2] | |
//N= number of elements in the array = number of bits of mask that should be checked | |
for(int i=0; i<N; i++ ) //check each bit of mask | |
{ | |
if(mask & (1<<i)) //if the i-th bit is set, then add it to sum | |
{ | |
sum+=array[i]; | |
} | |
} | |
cout<<sum<<endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment