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 

Permutations

Generates all permutation of n. Uses the naive (stupid) "let's generate all imaginable possibilities and see which are permutations" algorithm.

Time: O(n!)

   1  
   2  #include <stdio.h>
   3  
   4  int next(int v[], int n) {
   5  	int i = n - 1;
   6  	v[i] = v[i] + 1;
   7  	while ((i >= 0) && (v[i] > n)) {
   8  		v[i] = 1;
   9  		i--;
  10  		if(i >= 0)
  11  			v[i]++;
  12  	}
  13  
  14  	if (i < 0)
  15  		return 0;
  16  	return 1;
  17  }
  18  
  19  void printv(int v[],int n) {
  20  	int i;
  21  
  22  	for (i = 0; i < n; i++)
  23  		printf("%d", v[i]);
  24  	printf("\n");
  25  }
  26  
  27  int is_perm(int v[], int n) {
  28  	int i, j;
  29  
  30  	for (i = 0; i < n; i++)
  31  		for (j = i + 1; j < n; j++)
  32  			if (v[i] == v[j])
  33  				return 0;
  34  
  35  	return 1;
  36  }
  37  
  38  int main(int argc, char *argv[]) {
  39  	int v[128];
  40  	int n = 6;
  41  	int i;
  42  	for(i = 0; i <= n; i++)
  43  		v[i] = i + 1;
  44  
  45  	while (next(v,n))
  46  		if (is_perm(v,n))
  47  			printv(v,n);
  48  
  49  	return 0;
  50  }
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS