0

从此原始代码生成 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 个排列?

4

1 回答 1

0

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

如果您只想生成 10 个排列,请在 printf 时查看您的代码,并在每次 printf 排列时增加一个计数器,当计数器为 10 时中断 while

于 2013-08-26T14:49:13.950 回答