Need C Algorithm

John Lipinski lip at masscomp.UUCP
Fri Dec 14 01:53:14 AEST 1984


For Warren Lobel at Exxon Office Systems, who requested a solution 
to the permutation problem. The following C program takes a string 
as an argument and prints out the list of permutations.  It is a very
interesting algorithm.  

			- John Lipinski

------------------------------------------------------------------------

/* permutate: prints a list of all possible permutations of a string. */
/* usage: permutate string */

main(argc,argv)
int argc;
char **argv;
{
    char *word, *malloc();

    if (argc < 2) exit(1);
    word = malloc(strlen(argv[1]) + 2);
    strcpy(word,argv[1]);
    permutate(word,strlen(word)-1);
}

permutate(word,right)
char word[];
int right;
{
    int left;
    if (right > 0) {
	for(left = right; left >= 0; left--) {
	    swap(word,left,right);
	    permutate(word,right-1);
	    swap(word,left,right);
	}
	return;
    } else 
	printf("%s\n",word);
}

swap(s,l,r)
char s[];
int l, r;
{
    char c;
    c = s[l];
    s[l] = s[r];
    s[r] = c;
}



More information about the Comp.lang.c mailing list