Search code examples
ccombinationspermutationc-stringscpu-word

Finding possible permutations of a word


again. I've written a code on finding all possible combinations on a word and my code works but very limited times (i.e) it prints the string with "a" being only swapped (my I/P is abcd) but not b,c and d.

Code is duly attached. I plead you to help me.

#include<stdio.h>

void combination(char *,int,int);
int my_strlen(char *);
int main()
{
    char s[10];
    scanf("%[^\n]",s);
    int n=my_strlen(s);
    combination(s,0,n-1);
    return 0;
}
void combination(char *s,int i,int n)
{
    char c[10];
    for(int j=0;j<=n;j++)
        c[j]=s[j];
    int cn=0,k=0,l=0;
    while(s[k]!='\0')
    {
        i=0,cn=0;
        while(s[i]!='\0')
        {
            if(s[i]==c[i])
                cn++;
            i++;
        }
        if(--cn==n)
        {
            int m=l;
            while(m<n)
            {
                char temp=s[m];
                s[m]=s[m+1];
                s[m+1]=temp;
                printf("%s\n",s);
                m++;
            }
            l++;
        }
        k++;
    }
}
int my_strlen(char *s)
{
    int i=0,c=0;
    while(s[i++]!='\0')
        c++;
    return c;
}

I knew that my logic is incomplete but I expect atleast 18 combinations instead of 24, but it isn't going that way too (it prints only 3). So, I request my codies to help me complete my code, because I've just begun to delve deep into string concepts. I believe that controlling 'k' is the problem, but I couldn't find the way to control it.


Solution

  • There is a strlen() functional in string.h so I'm using that. Other than that, your code problem is that you only swap first characters. To fix this I'm using recursive.

    Swap a character with first character and then recursively call my permute method again. This code works fine for strings without repeated characters. To make it work for strings with repeated characters, it would be a little more complicated.

    #include <stdio.h>
    #include <string.h>
        
    void swap(char *x, char *y) {
        char temp;
        temp = *x;
        *x = *y;
        *y = temp;
    }
        
    void permute(char *a, int l, int end) {
        int i;
        if (l == end)
            printf("%s\n", a);
        else {
            for (i = l; i <= end; i++) {
                swap((a+l), (a+i));
                permute(a, l+1, end);
                swap((a+l), (a+i)); 
            }
        }
    }
        
    int main() {
        char str[10] = "";
        scanf("%9s", str);
        int n = strlen(str);
        permute(str, 0, n-1);
        return 0;
    }