Sunday, October 30, 2011

String permutation


// Stringpermutation.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
#include 
#include 
using namespace std;


void swap(char* a, char* b) 
{
 if (*a == *b ) return;

 char temp;
 temp = *a;
 *a = *b;
 *b = temp;
}

void permutate( char* Str, int index )
{
    int i = 0;
    if( index == strlen(Str)-1 )
    { 
       // We get a permutation, print it
        printf("%s \n",Str);
        return;
    }

 permutate(Str, index+1);

    for( i = index+1; i < strlen(Str); i++ )
    {

        int j;
        for( j = index;j < i;j++ )
            if( Str[j] == Str[i] )
                     break;
        if(j==i) 
        {
          swap( Str+index, Str+i ); 
          permutate( Str, index + 1 );
          swap( Str+index, Str+i );
        };

    }
}


int _tmain(int argc, _TCHAR* argv[])
{
 char str[] = "Abc";
 permutate( str, 0 );
 system("pause");

 char str2[] = "aabc";
 permutate( str2, 0 );
 system("pause");

 
 char str3[] = "acadc";
 permutate( str3, 0 );
 system("pause");

 return 0;
}


No comments: