Wednesday, June 19, 2013

Find Next Permutation of given string

Hi Guys,

Here is  the code to find the next permutation of given string. I used the algorithm mentioned by Career Cup and this is solution to IARCS.

So Here is the solution

#include
void nextPermutation(char a[], int size);
 
main()
{
    int Size;
    int length;
    char size[5];
    char string[2000];//here just assuming that there can be 1000 digit number and there will be space in between 2 numbers
    int i=0;
    int j=0;
    int k =0;
    int temp = 0;
    char tempstring[1000];
    //printf("Enter the size of array\n");
    fgets(size,5,stdin);
    //printf("entered string is = %s\n",size);
    Size = size[2] - '0';
    length = size[0] - '0';
    //printf("String length = %d and Size = %d\n",length,Size);
    for(i=0;i < Size; i++)
    {
        fgets(string,2000,stdin);
        j = k = 0;
        while(j<2000 amp="" code="" j="" string="">'\0')
        {
            if(string[j] != 32)
            {
                tempstring[k] = string[j];
                tempstring[++k] = '\0';
            }
            ++j;
        }
        //printf("So the number is = %s and the k = %d\n",tempstring,--k);
        nextPermutation(tempstring,--k);
    }
     
}
 
void nextPermutation(char arr[], int length)
{
    int i=0;
    int temp = 0;
    int pos, maxpos;
    pos = maxpos = -1;
    for(i=0; i
    {
        if(arr[i] < arr[i+1])
        {
            pos = i;
        }
    }
     
    if(pos == -1)
    {
        printf("No next Permutation exist\n");
        return;
    }
     
    for(i=pos+1;i < length;i++)
    {
        if(arr[pos] < arr[i])
            maxpos = i;
    }
    //printf("pos = %d and maxpos = %d and length = %d\n",pos,maxpos,length);
    //swap
    temp = arr[pos];
    arr[pos] = arr[maxpos];
    arr[maxpos] = temp;
     
    for(i=pos+1;i
    {
        temp = arr[i];
        arr[i] = arr[i+1];
        arr[i+1] = temp;
    }
     
    printf("So the next string is \n");
     
    for(i=0;i
        printf("%d ",arr[i]-'0');
    printf("\n");
}

No comments: