Advertisement
steverobinson

Steve Robinson | String Permutation

Jan 12th, 2011
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.76 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <stdio.h>
  4. void swap(char* src, char* dst)
  5. {
  6.         char ch = *dst;
  7.         *dst = *src;
  8.         *src = ch;
  9. }
  10. /* permute [set[begin], set[end]) */
  11. int permute(char* set, int begin, int end)
  12. {
  13.         int i;
  14.         int range = end - begin;
  15.         if (range == 1) {
  16.                 printf("set: %s\n", set);
  17.         } else {
  18.                 for(i=0; i<range; i++) {
  19.                         swap(&set[begin], &set[begin+i]);
  20.                         permute(set, begin+1, end);
  21.                         swap(&set[begin], &set[begin+i]);       /* set back */
  22.                 }
  23.         }
  24.         return 0;
  25. }
  26. int main()
  27. {
  28.         char str[] = "abcd";
  29.         permute(str, 0, strlen(str));
  30.         return 0;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement