gpt4 book ai didi

c - 循环遍历所有可能的长度为 n 的字符串

转载 作者:行者123 更新时间:2023-11-30 15:39:55 24 4
gpt4 key购买 nike

我正在编写一个程序,它必须循​​环遍历所有可能的字符串,最大长度为 n。这是它的代码。

int len, endlen = atoi(argv[2]);
int i, j, k;
f = fopen(argv[1], "wb");
for (len = 0; len < endlen; len++)
{
for (i = 0; i < len; i++)
{
for (k = 32; k < 127; k++)
{
entry.len = len;
string[i] = k;
memcpy(entry.string, string, 65);
sha256(string, entry.outbuf, len);
fwrite(&entry, sizeof(struct hashentry), 1, f);
fflush(f);
}
}
printf("\rLength done: %d of %d", len, endlen);
fflush(stdout);
}

只需修改字符串的一个索引即可返回。它需要做一些类似二进制计数的事情..

000
001
010 <--It moved over
011 <--Now it modified the previous one
100 <--moved again
101 <--Modifying previous
110
111 <--...etc

有什么帮助吗?

*编辑:我需要的是能给我从 size=1 到 size=endlen 的所有字符串的东西。这就像

"a"
"aa"
"aaa"
"aaaa"
"aaaaa"
or
"a"
"b"
"c"
...
"aa"
"ab"
"ac"
...
"aaaaa"
"aaaab"
"aaaac"
...
"abcde"

最佳答案

这里需要 endlen 嵌套循环。您可以使用递归方法避免显式编写它们:

void all_combinations( char* x, const int len )
{
for (char c = 65; c < 70; ++c){
x[len] = c;
if (len>0){
all_combinations( x, len - 1 );
} else {
printf( "%s\n", x );
}
}
}

int main()
{
const int maxlen = 3;
char x[maxlen+1];
for( int thislen=1; thislen<=maxlen; thislen++ ){
x[thislen] = 0;
all_combinations( x, thislen-1 );
}
}

关于c - 循环遍历所有可能的长度为 n 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21235264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com