#include #include #include #include void rol(char *s); void rol(char *s) { char ch = s[0]; memmove(s, s+1, strlen(s+1)); s[strlen(s)-1] = ch; } void ror(char *s); void ror(char *s) { char ch = s[strlen(s)-1]; memmove(s+1, s, strlen(s+1)); s[0] = ch; } int MAX; char *FIRST; char *PREV = NULL; #if 0 void perm(char *s); void perm(char *s) { int i; int ch; for (i=0; s[i]; i++) { if (strlen(s) > 1) { perm(s+1); } else { printf("%s\n", FIRST); #if 0 if (strcmp(PREV, FIRST)) { printf("%s\n", FIRST); strcpy(PREV, FIRST); } #endif } rol(s); } } #endif static char *OUT = NULL; static void addchr(int ch); static void addchr(int ch) { int len=strlen(OUT); OUT[len] = ch; OUT[len+1] = '\0'; } static void delchr(void); static void delchr(void) { int len=strlen(OUT); if (len >= 1) OUT[len-1] = '\0'; } static void perm(char *s); static void perm(char *s) { int i; for (i=0; s[i]; i++) { if (strlen(s+i) > 1) { perm(s+i+1); } if (strlen(s+i) == 1) { printf("%c", s[0]); printf("\n"); } } } #if 0 static void perm(char *s); static void perm(char *s) { int i; char *t = strdup(s); if (t == NULL) { fprintf(stderr, "perm(): strdup() failed.\n"); exit(-1); } if (strlen(s) == 0) { printf("%s\n", OUT); } else { for (i=0; t[i]; /* i++ */) { addchr(t[i]); /* Remove character 't[i]' from string: */ memmove(t+i, t+i+1, strlen(t+i+1)+1); perm(t); strcpy(t, s); delchr(); /* Get to next non-similar character: */ while (t[++i]) { if (t[i] != t[i-1]) break; } } } free(t); } #endif static int fcmp(void *p1, void *p2); static int fcmp(void *p1, void *p2) { return ((int)(*(char*)p1) - (int)(*(char*)p2)); } void main(int argc, char **argv) { if (argc > 1) { MAX = strlen(FIRST = argv[1]); if ((PREV = strdup(FIRST)) == NULL) { fprintf(stderr, "strdup() failed.\n"); exit(-1); } PREV[0] = '\0'; qsort((char*) argv[1], (size_t) MAX, sizeof(char), fcmp); #if 0 /* Set up so that duplicate permutations are always adjacent: */ rol(FIRST); #endif if ((OUT = malloc(MAX)) == NULL) { fprintf(stderr, "malloc() failed for OUT.\n"); exit(-1); } OUT[0] = '\0'; perm(argv[1]); } }