Oct 12, 2011

generating permutations - part deux

I was never too happy with my string permutation generation algorithm. I am happy to come back to this subject, and present a way more simpler algorithm to print permutations. I call this the 'rotating' & 'pinning' algorithm. It works by changing in the passed string (so its not immutable); and then restores back the original string before proceeding ahead (it uses back tracking).


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void swap(char *i1, char *i2) {
  char tmp = *i1;
  *i1 = *i2;
  *i2 = tmp;
}

/* algorithm
 * - rotating and pinning prefix substrings
 * - for example if "abc" is the string
 *   - rotate the letter 'a' in passed index 
 *     to remaining places in the string:(0,1,2)
 *   - foreach such combination
 *     - pin prefix; rotate remaining substring
 * 
 *       - abc - abc 
 *             - acb
 *   abc - bac - bac
 *             - bca
 *       - cba - cba
 *             - cab 
 */
void permute(char *s, int index) {
  if ( index == strlen(s) ) {
    printf("%s\n",s);
    return;
  }

  /* rotate s[index] from: index --> end of string */
  for(int i=index;i<strlen(s);i++) {
    swap(&s[index],&s[i]);
    /* pin substring from: 0 --> index+1 */
    permute(s,index+1);
    swap(&s[index],&s[i]);
  }
}

int main(int argc,char **argv) {
  if ( argc>1 ) {
    char *s = malloc(strlen(argv[1])+1);
    strcpy(s,argv[1]);
    permute(s,0);
  }
}

No comments: