Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

algorithm - Generate all strings under length N in C

I tried coding this myself and horribly failed. This is basically what I want:

a
b
...
z
aa
ba
...
za
ab
bb
...
zz
aaa
baa
...
zzz

In the end it should have generated every string that is shorter then N characters with charset a-z. So I'm not looking for permutations (of which 1001 implementations can be found on the internet), but for combinations with replacement (at least that's how it's called in Python). Order is not important, speed is.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Looks like you want it in C, here is a way to do it:

#include <stdlib.h>
#include <stdio.h>

int inc(char *c){
    if(c[0]==0) return 0;
    if(c[0]=='z'){
        c[0]='a';
        return inc(c+sizeof(char));
    }   
    c[0]++;
    return 1;
}

int main(void){
    int n = 3;
    int i,j;
    char *c = malloc((n+1)*sizeof(char));
    for(i=1;i<=n;i++){
        for(j=0;j<i;j++) c[j]='a';
        c[i]=0;
        do {
            printf("%s
",c);
        } while(inc(c));
    }
    free(c);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...