Generate all lines by length N in C

I tried to code this myself and terribly failed. This is basically what I want:

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

In the end, he had to generate every line that is shorter than N characters encoded with az. Therefore, I am not looking for permutations (of which 1001 implementations can be found on the Internet), but for combinations with replacement (at least how it was called in Python), Order is not important , speed.

+7
source share
2 answers

It 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\n",c); } while(inc(c)); } free(c); } 
+9
source

Something like this (pseudo code):

 void CompWithRep(string line,int N) { char c; if (N==0) return; for (c = 'a' ; c <= 'z' ; c++ ) { printf(line + c); CompWithRep(line + c,N-1); } } 
+3
source

All Articles