2014-01-20 75 views
0

我有一个程序,我正在编写它必须遍历所有可能的字符串到n的大小。这是它的代码。循环遍历所有可能的字符串的长度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" 
+1

您会得到什么输出? – suspectus

+0

你的问题不清楚 – exexzian

+0

如果你计算你的两个iner loop,你只能得到len * 96的迭代次数。这太低了,无法获得所有96^len的组合。 你需要len嵌套循环(或等价的东西,最有可能是一个递归函数)通过​​所有的组合。顺便说一下,这很快就会变成一个令人愤慨的数字(在endlen 9中,你会得到几十万亿字符串)。 – lrn

回答

1

这里需要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); 
    } 
} 
+0

你能解释65和70从哪里来? – phyrrus9

+0

对不起。我不认为这个观点正确。我需要它从长度= 1到长度= len找到所有字符串。这包括(比如len = 5)“a”和“aaaaa”。 – phyrrus9

+0

然后你可以在循环中运行'all_combinations'作为最后一个参数'1,2,..,len'。 – zoska