通过代的排列

时间:2013-08-26 14:34:40

标签: c char

从这个原始代码生成3个数字的所有可能组合:

void gen(char *word, char *chars, int ug, int length) {
    size_t i = 0;
    int u = ug;
    while(i < strlen(chars)){
        word[u] = chars[i++];

        if(u < (length-1)) {
            gen(word, chars, ++u, length);
            u--;
        } else {
            printf("%s\n", word);
        }
    }
}

int main(int argc, char* argv[]) {

    char *chars = "0123456789";
    /* 3 char long */
    int i = 3;

    int length = 3;
    /* Allocate memory for the output */
    char *word = calloc(length, 0);

    gen(word, chars, 0, 3);
    return 0;
}

但是因为我需要以不同的方式工作,我修改了它:

char *genpass(char* pass,int len, int crt, size_t i) {
    char *chars = "0123456789";
    pass[crt] = chars[i++];
    return pass;
}


int main(int argc, char* argv[]) {
    char *pass = calloc(10, 0);
    int crt;//current permutation
    int len = 3;
    size_t i = 0;
    for (crt=0;crt<10;crt++)
    {
        pass = genpass(pass,len,crt,i);
        printf("pass: %s\n", pass);
        i++;
        //some other code to work with pass
    }
    return 0;
}

但现在又回来了:

pass: 0
pass: 01
pass: 012
pass: 0123
pass: 01234
pass: 012345
pass: 0123456
pass: 01234567
pass: 012345678
pass: 0123456789

我搞砸了什么?如何才能正确生成3个长度数的前10个排列?

1 个答案:

答案 0 :(得分:0)

现在你的函数genpass()不是递归的!

如果你只想生成10个排列,那么当你打印某个东西时查看你的代码并在每次打印一个排列时增加一个计数器,当计数器是10时打破这个时间