summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/SNIP/permute2.c
blob: 2cad78a27bb3cfd7b0333f9fea9d1e2990039828 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
**  PERMUTE.C - prints all permutations of an input string
**
**  public domain demo by Jon Guthrie
*/

#include    <string.h>
#include    <stdlib.h>
#include    <stdio.h>

int     charcmp(char *, char *);

void    permute(char *, int, int);

int     main(int argc, char *argv[])
{
      int length;

      if (2 > argc)
      {
            puts("Usage: PERMUTE string");
            abort();
      }
      
      length = strlen(argv[1]);

      /* It only works if they're printed in order */

      qsort(argv[1], length, 1, (int(*)(const void *, const void *))charcmp);

      permute(argv[1], 0, length);
      return 0;
}


/*
**  This function prints all of the permutations of string "array"
**  (which has length "len") starting at "start."
*/

void    permute(char *array, int start, int len)
{
      int j;
      char    *s;

      if(start < len)
      {
            if(NULL == (s = malloc(len)))
            {
                  printf("\n\nMemory error!!!\a\a\n");
                  abort();
            }

            strcpy(s, array);
            for(j=start ; j<len ; ++j)
            {
                  int     temp;

                  if((j == start) || (s[j] != s[start]))
                  {     /* For each character that's different    */
                        /* Swap the next first character with...  */
                        /* the current first                      */
                        temp = s[j];
                        s[j] = s[start];
                        s[start] = temp;
                        permute(s, start+1, len);
                  }
            }
            free(s);
      }
      else	puts(array);
}



int charcmp(char *a, char *b)
{
      return(*a - *b);
}