/* This program prints out all the permutations of the 
 * first command line argument.   After David Albrecht, 16/2/2001
 */

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

void permute(char str[], int level, int length);


main(int argc, char* argv[])
{ if (argc > 1)
    permute(argv[1], 0, strlen(argv[1]));
}


/* swap str[i] and str[j] */
void swap(char str[], int length, int i, int j)
{ char tmp;

  if (i >= 0 && i < length && j >= 0 && j < length)
  { tmp = str[i];
    str[i] = str[j];
    str[j] = tmp;
  }
}


/* print all permutations of str */
void permute(char str[], int level, int length)
{ int i;
   
  if (level >= length) /* complete - print a permutation */
    printf("%s\n", str);

  else /* continue construction of the permutations */
  { permute(str, level+1, length);  

    for (i = level+1; i < length; i++)
    { swap(str, length, i, level);    /* swap str[i] and str[level] */
      permute(str, level+1, length);  /* different permutation      */
      swap(str, length, i, level);    /* swap str[i] and str[level] */
    }
  }
}

