开发者

permutations and combinations [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist

Closed 9 years ago.

Improve this question

I have a program which creates some combinations of strings like if I entered input abc it gives me output as bca cab abc

#include<stdio.h>
#include<string.h>
int main()
{
    char str[15];
    int i,开发者_JAVA百科j,n;

    printf("Enter a string");
    scanf("%s",str);
    n=strlen(str);

    for(i=0;i<n;i++)
    {
        str[n]=str[0];

        for(j=0;j<n;j++)    
        {
            str[j]=str[j-1];
        }
    str[n]='\0';
    printf("\n %s \n",str);
    }
    return 0;
}

But I want a program which gives me all possible combinations of a string so what are the changes I need to make?


Use the Exeter algorithm

#include <stdio.h>
#include <string.h>

void swap(char *x, char *y){
    char w;
    w = *x;
    *x = *y;
    *y = w;
}

void permute(char *str, int start, int n){
    int i;

    if(start == n-1)
        printf("%s\n", str);
    else
        for(i = start; i < n; i++){
            swap(str+i, str+start);
            permute(str, start+1, n);
            swap(str+i, str+start);
        }
}

int main(){

    char line[10], str[10];
    int n, op;

    printf("Enter a string: ");
    if( fgets(line, 10, stdin) == NULL ){
        printf("Ops! Early stop\n");
        return 1;
    }


    if( sscanf(line, "%s", str) != 1 ){
        printf("Next time put some valid characters\n");
        return 1;
    }

    n = strlen(str);
    permute(str, 0, n);
    return 0;
}

Note: This algorithm generates all the possibles permutations

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜