Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Alexandru Scvortov

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Generate all subsets of a set

This code generates all the subsets of {1, 2, ..., n} and prints them.

This also contains a very fast binary counter implementation.

See this for further explanations.

   1  
   2  #include <stdio.h>
   3  
   4  /* Applies the mask to a set like {1, 2, ..., n} and prints it */
   5  void printv(int mask[], int n) {
   6  	int i;
   7  	printf("{ ");
   8  	for (i = 0; i < n; ++i)
   9  		if (mask[i])
  10  			printf("%d ", i + 1); /*i+1 is part of the subset*/
  11  	printf("\b }\n");
  12  }
  13  
  14  /* Generates the next mask*/
  15  int next(int mask[], int n) {
  16  	int i;
  17  	for (i = 0; (i < n) && mask[i]; ++i)
  18  		mask[i] = 0;
  19  
  20  	if (i < n) {
  21  		mask[i] = 1;
  22  		return 1;
  23  	}
  24  	return 0;
  25  }
  26  
  27  int main(int argc, char *argv[]) {
  28  	int n = 3;
  29  
  30  	int mask[16]; /* Guess what this is */
  31  	int i;
  32  	for (i = 0; i < n; ++i)
  33  		mask[i] = 0;
  34  
  35  	/* Print the first set */
  36  	printv(mask, n);
  37  
  38  	/* Print all the others */
  39  	while (next(mask, n))
  40  		printv(mask, n);
  41  
  42  	return 0;
  43  }
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS