Re: Combination of binary variables
- From: "Gene" <gene.ressler@xxxxxxxxx>
- Date: 29 Mar 2007 21:51:45 -0700
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;
}
.
- References:
- Combination of binary variables
- From: Nightfall
- Combination of binary variables
- Prev by Date: Re: bison and valgrind
- Next by Date: Re: bison and valgrind
- Previous by thread: Re: Combination of binary variables
- Next by thread: Re: Combination of binary variables
- Index(es):
Relevant Pages
|