I'm looking for an algorithm in C to generate all possible variations with repetitions for set length and from n elements. For example, if the length is 3 and the elements are: 1, 2. The output should be :
1 1 1
1 1 0
1 开发者_JS百科0 0
1 0 1
0 0 0
0 0 1
0 1 1
0 1 0
I already looked for the solutions here, but all I could find were implementations in Java or Python and I don't know how to rewrite them to C. Can somebody please post a C code for this problem here?
void g(int l,int v,char *c)
{
int i=v;
if (l--==0)
puts(c);
else
while(i)
g(l,(c[l]='0'+--i,v),c);
}
void f(int l,int v)
{
char c[l+2];
g(((c[l]=13,c[l+1]=0),l),v,c);
}
int main()
{
f(3,2);
return 0;
}
Tested, works!, updated to fix readability issue
It's nothing else than generating all the numbers of length N
in base B
(in your case N is 3 and B is 2).
精彩评论