c - 传递生成的排列

标签 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 个排列?

最佳答案

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

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

关于c - 传递生成的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18446650/

相关文章:

c - void 元素上的指针减法

c - 基数排序优化

c 字符串基础知识,为什么未分配?

c++ - 拆分并分配字符

c - "expected ' =', ' ,', ' ;', ' asm' 或 '__attribute__' 之前的 'char' 是什么意思? AVR

c++ - C++ 库是否依赖于 C 库? (对于 GCC 和 linux 的情况)

c - 如何访问另一个结构中的结构变量?

java - 让 JNA 在 Java 1.4 下工作

c - C11 中什么算作字符类型?

C - 新分配的 char* 包含现有数据