Monday, July 27, 2009

Permutation Combination algorithm / C

Here is the code that i've written for Permutation on C. Hope this helps..
let me know if anyone finds any better way(less time consuming) to do it...


Permutation Combination Code on C / Algorithm

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

int str_len(char *s){
//this function returns the length of an string pointer.
int l=0;
while (*s!='\0'){
*s++;
l++;
}
return(l);
}

void str_left(char *t, char *s,int p=1){
//this function copys a string from a certain number
//from the left to the end to another string.
int len;
len=str_len(s);
s=s+p;
for(int i=p;i<len;i++){
*t++=*s++;
}
*t='\0';
}

void str_step(char *s){
//this function cycles all the letters in a string one
//step forward..last letter comes in the front.
int len;
char k1,k2;
len=str_len(s);
k1=*s;
*s=*(s+len-1);
s++;
while(*s!='\0'){
k2=*s;
*s=k1;
s++;
k1=k2;
}
}

void str_replace(char *t,char *s){
//this function copies one string into another string from
//the left(target string should have greater or equal length).
int lt,ls;
ls=str_len(s);
lt=str_len(t);
t=t+(lt-ls);

while(*s!='\0'){
*t++=*s++;
}

}

 

void str_permutation(char t[],int first=1){
//this is the function that does the permutation
static char current[20];
static int count;
int len=strlen(t);
if (first==1){
strcpy(current,t);
count=0;
}


 if(len>2){
for (int i=0;i<len;i++){
char temp[20];
str_left(temp,t);
str_replace(current,t);
str_permutation(temp,0);
str_step(t);
}
}else{
for(int j=0;j<2;j++){
str_replace(current,t);
count++;
printf("%s | ",current);
str_step(t);
if((count%5)==0){
printf("\n");
}
}
}
if (first==1){
printf("\n%d\n",count);
}
}


void main(){
while(1){
char s[20];
gets(s);
str_permutation(s);
}
}

1 comment:

  1. I would like to draw your attention to article:
    http://www.docstoc.com/docs/8462068/Permutation-Combination-GMAT-Notes

    ReplyDelete