View Single Post
Old Jan 19th, 2008, 12:04 AM   #7
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,886
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
Re: Recursive permutation of string

I was very much confused, because you said "reverse" instead of "recurse" in your initial post at one point. So I was assuming there was some complicated problem statement missing. Okay.

The key is to keep track of what you haven't added. See how the tree stems apart, and what data you want to keep track of. This algorithm can be proven qualitatively by drawing the trees. It can be proven mathematically by subproblems and dynamic programming. I'll leave that excercise up to you.

Edit: In reference to your question about doing it without copying new strings: I do not believe so. This is due to the nature of dynamic programming and subproblems. If you look at the tree the reason becomes obvious. But there might be some fancy ways. Such as brute forcing it iteratively, and checking for invalid entries. So I doubt any other solutions would be efficient in any case. But I am not sure.


Here it is in C:

C Syntax (Toggle Plain Text)
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. void permutate(char *s, char *r, int k, int n) {
  6. int i;
  7. char *new_s;
  8. if (k==n) { // At the end
  9. r[n] = 0; // Add a null terminator
  10. printf("%s\n", r); // Output result
  11. return;
  12. }
  13. for(i=0;i<n;i++) {
  14. if (s[i]) {
  15. new_s = calloc(sizeof(char), n);
  16.  
  17. // Use memcpy to ignore the null terminators
  18. memcpy(new_s, s, sizeof(char) * (n+1));
  19. new_s[i] = 0; // Mark used character
  20. r[k] = s[i]; // Store used character
  21. permutate(new_s, r, k+1, n);
  22. free(new_s);
  23. }
  24. }
  25. }
  26.  
  27. int main() {
  28.  
  29. char str[] = "abc";
  30. char *result_str = calloc(sizeof(char), strlen(str) + 1);
  31.  
  32. permutate(str, result_str, 0, strlen(str));
  33. return 0;
  34. }

Last edited by Sane; Jan 19th, 2008 at 12:17 AM.
Sane is offline   Reply With Quote