fork(2) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int c = 0;
  5.  
  6. void foo(char *s1, char *s2, int n) {
  7. int j;
  8. if (*s1 == '\0') {
  9. c++;
  10. printf("foo %03d %s\n", c, s2);
  11. } else {
  12. for (j = 0; j < n; j++) {
  13. if (s2[j] == '\0') {
  14. s2[j] = *s1;
  15. foo(s1 + 1, s2, n);
  16. s2[j] = '\0';
  17. }
  18. }
  19. }
  20. }
  21.  
  22. void bar(char *s1, char *s2, int n) {
  23. int *st = (int*)calloc(n + 1, sizeof(int));
  24. int i, j, p, f, c;
  25. i = j = p = c = 0;
  26. f = 1;
  27. while (f) {
  28. if (s2[j] == '\0') {
  29. s2[j] = s1[i];
  30. i++;
  31. if (i == n) {
  32. c++;
  33. printf("bar %03d %s\n", c, s2);
  34. s2[j] = '\0';
  35. i--;
  36. j++;
  37. } else {
  38. st[p] = j;
  39. p++;
  40. j = 0;
  41. }
  42. } else {
  43. j++;
  44. }
  45. while (j == n) {
  46. i--;
  47. if (i < 0) {
  48. f = 0;
  49. break;
  50. }
  51. p--;
  52. j = st[p];
  53. s2[j] = '\0';
  54. j++;
  55. }
  56. }
  57. free(st);
  58. }
  59.  
  60. int main(void) {
  61.  
  62. char str1[] = "ABCD";
  63. char *str2 = (char*)calloc(strlen(str1) + 1, sizeof(char));
  64.  
  65. foo(str1, str2, (int)strlen(str1));
  66. bar(str1, str2, (int)strlen(str1));
  67.  
  68. free(str2);
  69.  
  70. return 0;
  71. }
  72.  
Success #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
foo 001 ABCD
foo 002 ABDC
foo 003 ACBD
foo 004 ADBC
foo 005 ACDB
foo 006 ADCB
foo 007 BACD
foo 008 BADC
foo 009 CABD
foo 010 DABC
foo 011 CADB
foo 012 DACB
foo 013 BCAD
foo 014 BDAC
foo 015 CBAD
foo 016 DBAC
foo 017 CDAB
foo 018 DCAB
foo 019 BCDA
foo 020 BDCA
foo 021 CBDA
foo 022 DBCA
foo 023 CDBA
foo 024 DCBA
bar 001 ABCD
bar 002 ABDC
bar 003 ACBD
bar 004 ADBC
bar 005 ACDB
bar 006 ADCB
bar 007 BACD
bar 008 BADC
bar 009 CABD
bar 010 DABC
bar 011 CADB
bar 012 DACB
bar 013 BCAD
bar 014 BDAC
bar 015 CBAD
bar 016 DBAC
bar 017 CDAB
bar 018 DCAB
bar 019 BCDA
bar 020 BDCA
bar 021 CBDA
bar 022 DBCA
bar 023 CDBA
bar 024 DCBA