Re: Combination of binary variables
- From: CBFalconer <cbfalconer@xxxxxxxxx>
- Date: Thu, 29 Mar 2007 21:01:31 -0500
Nightfall wrote:
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
I have to implement this algorithm in Mosel language (the
language used in Xpress-Optimizer), but this does't matter:
can you help me with just some "pseudo-code", please?
Here's some real code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* Public domain, by C.B. Falconer. *//* 2003-Aug-21 */
/* Attribution appreciated. */
/* Things get out of hand when larger than 8 */
#define MAXWORD 12
/* ------------------ */
/* exchange 0th and ith char in wd */
void trade(char *wd, unsigned int i)
{
char c;
c = *wd;
*wd = wd[i];
wd[i] = c;
} /* trade */
/* ------------------ */
/* Form all n char permutations of the characters in the
string wd of length lgh into outstring at index ix.
Output the results to stdout. */
void jumble(char *wd, unsigned int lgh,
unsigned int ix, /* output place to fill */
unsigned int n, /* max out places to fill */
char *outstring)
{
unsigned int i;
if (0 == n) {
outstring[ix] = '\0';
puts(outstring);
}
else
for (i = 0; i < lgh; i++) {
trade(wd, i); /* nop when (0 == i) */
outstring[ix] = *wd;
jumble(wd+1, lgh-1, ix+1, n-1, outstring);
trade(wd, i); /* restore the wd string */
}
} /* jumble */
/* ------------------ */
int main(int argc, char *argv[])
{
unsigned int n, lgh, min;
double max;
char outstring[MAXWORD];
if (argc < 2) {
fprintf(stderr,
"Usage: jumble <baseword> [lgh]\n"
" where the (optional) lgh specifies the\n"
" maximum length of the output words\n");
return 0;
}
lgh = strlen(argv[1]);
if (lgh >= MAXWORD) argv[1][lgh = MAXWORD-1] = '\0';
min = lgh;
if ((argc > 2) && (1 == sscanf(argv[2], "%u", &n)))
if (n && (n <= lgh)) min = n;
for (n = lgh, max = 1.0; n > (lgh - min); n--)
max = max * n;
fprintf(stderr, "string=\"%s\", max=%.0f, len=%u\n",
argv[1], max, min);
jumble(argv[1], lgh, 0, min, outstring);
return 0;
} /* main */
--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
--
Posted via a free Usenet account from http://www.teranews.com
.
- References:
- Combination of binary variables
- From: Nightfall
- Combination of binary variables
- Prev by Date: Re: Combination of binary variables
- Next by Date: Re: Combination of binary variables
- Previous by thread: Re: Combination of binary variables
- Next by thread: Re: Combination of binary variables
- Index(es):
Relevant Pages
|