-1

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 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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
boone
  • 41
  • 2
  • 2
    "I don't know how to rewrite them to C" I assume the purpose of your assignment is to learn to write enough C to do the job. What have you tried? If you don't know enough to write this, what will you do with the code you receive? Represent it as your own? – The Archetypal Paul Dec 02 '10 at 17:21
  • @Paul: agree. @anoob: try in english first. – ruslik Dec 02 '10 at 17:22
  • 2
    "Can somebody please post a C code for this problem here?" No; the reason you're being asked to do this is so that you actually learn something. – Karl Knechtel Dec 02 '10 at 17:29

2 Answers2

4
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

Darius Kucinskas
  • 10,193
  • 12
  • 57
  • 79
The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
  • 1
    And it better work, it's easier to write a new one than to debug **THIS** :) – ruslik Dec 02 '10 at 17:45
  • I could see somebody being dropped off the subject, oh dear. – Andreas Wong Dec 02 '10 at 17:54
  • By the way, last I checked, over 10 years ago that is, `char c[l+2];` was not standard C. Unless the standard has changed, this just something gcc lets you get away with. – Dima Dec 03 '10 at 15:59
  • Dima, you've removed the entire pont of my post. If you're going to do that, finish the job and rename the variables, remove the comma-expressions etc. I'm rolling back your change. – The Archetypal Paul Dec 03 '10 at 16:01
  • And it is allowed in C99 - http://stackoverflow.com/questions/448844/variable-sized-arrays-in-c – The Archetypal Paul Dec 03 '10 at 16:03
2

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).

ruslik
  • 14,714
  • 1
  • 39
  • 40