Saturday 28 July 2012

Write a program to permute a given string without recursion.



#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define display(X) printf( "\n%s", X );


/**
to remove new line from input string.
*/
void remove_newline( char* input )
{
    char* p = 0 ;
    if( p = strrchr( input, '\n' ) )
        *p = '\0' ;
}


void swap(char* a, char* b)
{
  char temp = *a;
*a = *b;
*b = temp;
}


/**
to permutate string without recursion.
*/
void wordPermutation (const char* input)
{
    int str_len = strlen(input) ;
if ( str_len == 0) /**if string is of zero length.*/
return ;
    /** this one for guard.*/
    char* p = (char*) malloc( str_len);
    {
        int j ;
        for( j = 0; j < str_len; ++j )
            p[j] = j ;
    }


 char* tmp_Buffer = (char*) malloc( str_len + 1 );
strcpy (tmp_Buffer, input);


    /** core algorithm begins */
int i = 1, j = 0;
printf( "\n%s", tmp_Buffer ) ;
while(i < str_len)
{
   p[i]--;
   j = i % 2 * p[i];
   swap( &tmp_Buffer[i], &tmp_Buffer[j] );
   display(tmp_Buffer);


   i = 1;
   while (!p[i])
   {
       p[i] = i;
       i++;
        }
   }
   /** core algorithm ends*/
   printf("\n");
   free( tmp_Buffer ) ;
   free( p ) ;
}


int main ( )
{
 char buffer[BUFSIZ]={'\0'};
printf ("\nEnter the string : \n");
fgets (buffer, BUFSIZ, stdin);
remove_newline (buffer);
wordPermutation (buffer);
return 0;
}

No comments:

Post a Comment