• Source
    1. #include <stdio.h>
    2.  
    3. // To enable debug messages uncomment #define
    4. #define TEST 1
    5. //#define DEBUG 1
    6.  
    7. #ifdef DEBUG
    8. # define D(x) x
    9. #else
    10. # define D(x)
    11. #endif
    12.  
    13. void permute(char *s, int start, int end);
    14. void swap(char *s, int start, int end);
    15. void startTesting();
    16.  
    17. int main(void) {
    18. #ifdef TEST
    19. startTesting();
    20. #endif
    21.  
    22. return 0;
    23. }
    24.  
    25. void swap(char *s, int start, int end) {
    26. char temp = s[start];
    27. s[start] = s[end];
    28. s[end] = temp;
    29. }
    30.  
    31. void permute(char *s, int start, int end) {
    32. int i = 0;
    33.  
    34. if (start == end) {
    35. printf("%s\n", s);
    36. D(printf("\n############\n"));
    37. } else {
    38. for (i = start; i <= end; i++) {
    39.  
    40. D(printf("Fix '%c' instead of '%c'\n", s[j], s[start]));
    41. swap(s, start, i);
    42.  
    43. D(printf("Call Permute on string %s from '%c' to '%c'\n", s, s[start + 1], s[end]));
    44.  
    45. permute(s, start + 1, end);
    46.  
    47. D(printf("Backtrack swap '%c' & '%c'\n", s[start], s[j]));
    48. swap(s, start, i);
    49. D(printf("After Backtrack string %s\n", s));
    50. }
    51. }
    52. }
    53.  
    54. void test1()
    55. {
    56. char s[] = "ABCD";
    57. printf("permute(\"%s\", 0, 3)\n", s);
    58. permute(s, 0, 3);
    59. printf("\n");
    60. }
    61.  
    62. void startTesting()
    63. {
    64. test1();
    65. }