Guest User

Untitled

a guest
Nov 18th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. /*
  2. * Print all permutations of a string,
  3. * using a tree-recursive routine. I
  4. * bet there are smart algorithms out
  5. * there that beat this. I did not look
  6. * up an algorithm when writing this.
  7. *
  8. * Bl0ckeduser
  9. * June 26, 2012
  10. */
  11.  
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15.  
  16. #define N 16
  17.  
  18. void fail(char* s){
  19. puts(s); exit(1);
  20. }
  21.  
  22. void permut(int n, char avail[], char prev[])
  23. {
  24. int i, j;
  25. char child_avail[N];
  26. char chars[N];
  27.  
  28. /* go through all available characters */
  29. for(i = 0; avail[i]; i++)
  30. if(avail[i] != '!') {
  31. /* found an available character;
  32. cross it out from the child's
  33. available characters list */
  34. strcpy(child_avail, avail);
  35. child_avail[i] = '!';
  36.  
  37. /* add the character to this
  38. permutation-string */
  39. strcpy(chars, prev);
  40. strncat(chars, &avail[i], 1);
  41.  
  42. /* print out permutation-string
  43. if a leaf is reached; otherwise,
  44. spawn child */
  45. if(n == 1)
  46. puts(chars);
  47. else
  48. permut(n - 1, child_avail, chars);
  49. }
  50. }
  51.  
  52. int main(int argc, char** argv)
  53. {
  54. char set[N];
  55.  
  56. if(scanf("%s", set) == EOF)
  57. fail("failed to input string");
  58.  
  59. if(strlen(set) > N)
  60. fail("string bigger than hardcoded limit");
  61.  
  62. if(strstr(set, "!"))
  63. fail("! is used internally");
  64.  
  65. permut(strlen(set), set, "");
  66.  
  67. return 0;
  68. }
Add Comment
Please, Sign In to add comment