0

I found this iterative algorithm that prints the power set for a given set:

void PrintSubsets() 
{ 
   int source[3] = {1,2,3}; 
   int currentSubset = 7; 
   int tmp; 
   while(currentSubset) 
   { 
      printf("("); 
      tmp = currentSubset;

      for(int i = 0; i<3; i++) 
      { 
         if (tmp & 1) 
         printf("%d ", source[i]); 
         tmp >>= 1; 
      } 
      printf(")\n"); 
      currentSubset--; 
   } 
}

However, I am not sure why it works. Is it similar to a solution where you use a set of n bits, and on each step, add 1 with carry, using the reuslting pattern of zeros and ones to determine which elements belong?

2
  • 2
    Yes, it's just like the case you describe using addition, except this one uses subtraction. Note that this implementation fails to output the empty set. Commented Sep 29, 2014 at 23:29
  • @GregHewgill Got it now. Feel free to just post that as an answer and I'll accept it. Commented Sep 29, 2014 at 23:40

1 Answer 1

1

List all integers in the binary base, and light should shine:

 {abc}
7 xxx
6 xx-
5 x-x
4 x--
3 -xx
2 -x-
1 --x
0 --- (omitted)

The order to enumerate the integers does not matter provided you list them all. Incrementing or decrementing are the most natural ways.

Sign up to request clarification or add additional context in comments.

1 Comment

Little challenge: list the partitions in Gray order, i.e. a single bit changes every time: 111, 110, 100, 101, 001, 011, 010, 000. Do this sequentially.

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.