Re: Combination of binary variables



On Mar 29, 5:17 pm, "Nightfall" <chesbo...@xxxxxxxxx> wrote:
Dear friends,
this is my problem: let's take an array of n binary variables. I need
an algorithm to write every possible combination of those variables.

If, say, n = 3, the algorithm should output:

000
001
010
100
011
110
101
111


It doesn't get the order exactly the same as your example, but this
method has a nice symmetry.
------------------------
#include <stdio.h>

char buf[10000];
char i;

void fill(int n0s, int n1s)
{
if (n0s == 0 && n1s == 0)
printf("%.*s\n", i, buf);
if (n0s > 0) {
buf[i++] = '0';
fill(n0s - 1, n1s);
i--;
}
if (n1s > 0) {
buf[i++] = '1';
fill(n0s, n1s - 1);
i--;
}
}

int main(int argc, char *argv[])
{
int n1s, len = 3;
if (argc > 2 || argc == 2 && sscanf(argv[1], "%d", &len) != 1)
printf("usage: %s [length]\n", argv[0]);
else
for (n1s = 0; n1s <= len; n1s++) fill(len - n1s, n1s);
return 0;
}

.



Relevant Pages