fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. int permutation(char nchars[], char result[], int count, int max);
  5. void arrayPrint(char a[], int count);
  6.  
  7. int permutation(char nchars[], char result[], int count, int max) {
  8. int i;
  9. int j;
  10. char *remain;
  11.  
  12. if (count == max) {
  13. arrayPrint(result, max);
  14. return EXIT_SUCCESS;
  15. }
  16.  
  17. for (i = 0; i < max - count; i++) {
  18. remain = calloc(max - count, sizeof(char));
  19.  
  20. for (j = 0; j < max - count; j++) {
  21. remain[j] = nchars[j];
  22. }
  23.  
  24. result[count] = remain[i];
  25.  
  26. for (j = i + 1; j < max - count; j++) {
  27. remain[j - 1] = remain[j];
  28. }
  29.  
  30. permutation(remain, result, count + 1, max);
  31.  
  32. free(remain);
  33. }
  34.  
  35. return EXIT_SUCCESS;
  36. }
  37.  
  38. void arrayPrint(char a[], int count) {
  39. int i;
  40.  
  41. for (i = 0; i < count; i++) {
  42. printf("%c", a[i]);
  43. if (i < count - 1) {
  44. printf(",");
  45. } else {
  46. printf("\n");
  47. }
  48. }
  49. }
  50.  
  51. int main(int argc, char *argv[]) {
  52. char *chars = "abcdefghijklmno";
  53. char *nchars;
  54. char *result;
  55. int n;
  56. int i;
  57.  
  58. /* n = atoi(argv[1]); */
  59. n = 5;
  60.  
  61. nchars = calloc(n, sizeof(char));
  62. result = calloc(n, sizeof(char));
  63.  
  64. for (i = 0; i < n; i++) {
  65. nchars[i] = chars[i];
  66. }
  67.  
  68. permutation(nchars, result, 0, n);
  69.  
  70. free(result);
  71. free(nchars);
  72.  
  73. return EXIT_SUCCESS;
  74. }
Success #stdin #stdout 0.01s 1852KB
stdin
Standard input is empty
stdout
a,b,c,d,e
a,b,c,e,d
a,b,d,c,e
a,b,d,e,c
a,b,e,c,d
a,b,e,d,c
a,c,b,d,e
a,c,b,e,d
a,c,d,b,e
a,c,d,e,b
a,c,e,b,d
a,c,e,d,b
a,d,b,c,e
a,d,b,e,c
a,d,c,b,e
a,d,c,e,b
a,d,e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