Search code examples
ccstringc-strings

Looping through all possible strings of length n


I have a program I am writing that has to loop through all possible strings up to size n. Here is the code for it.

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);
}

It is coming back with just modifying one index of the string. It needs to do something a lot like counting in binary..

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

Any help?

*edit: What I need is something that will give me all strings from size=1 to size=endlen. This would be like

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

Solution

  • You need endlen nested loops here. You can avoid writing them explicitely by using a recursive approach:

    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 );
        }
    }