Wednesday, 16 May 2012

Write a C program to generate all possible permutation of a string.

Underlying concept: Recursion
Assignment: Generate all possible Combinations of a string (Its to remind you  that combination is different from permutation)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int cnt=0;
void permutate(char *cut,char *c)
{
    char d,keep[20];
    int i,j;
    strcpy(keep,cut);
    int len=strlen(cut);   
    d=c[len];
    if(d=='\0')
    {
        printf("%d.%s\n*****\n",++cnt,cut);
        return ;
    }
       
    for(i=len;i>=0;--i)
    {
        for(j=len;j>=i;j--)
            cut[j+1]=cut[j];
        cut[++j]=d;
        permutate(cut,c);
        strcpy(cut,keep);
    }

   
}


       
int main()
{
    char *c,*cut;
    int n;
    printf("\n Enter n:");
    scanf("%d",&n);
    c=(char*)malloc(n*sizeof(char));
    cut=(char*)malloc(n*sizeof(char));
    printf("Enter the string:");
    scanf("%s",c);
    cut[0]=c[0];
    cut[1]='\0';
    permutate(cut,c);
    return 0;
}

0 comments

 
© 2011-2012 ProgrammingBlue
Posts RSS Comments RSS
Back to top