Power set: Difference between revisions

Content added Content deleted
(Added Oz solution.)
(Add C)
Line 151:
}
MsgBox % RegExReplace(SubStr(t,1,StrLen(t)-1),",}","}")</lang>
 
=={{header|C}}==
<lang c>#include <stdio.h>
#include <stdlib.h>
 
typedef char *SetType;
typedef int bool;
 
typedef struct setStruct {
int count;
SetType *elements;
void (*printer)(SetType );
bool nlAfterElements;
} *Set;
 
/* Could probly use same struct as above for this */
typedef struct powerSetStruct {
int count;
Set *elements;
void (*printer)(Set);
bool nlAfterElements;
} *PowerSet;
 
void PrintSet( Set s);
 
PowerSet GetPowerSet( Set set)
{
int ix, n, j;
int max = 1<<set->count; // Assuming count < 32
 
PowerSet ps = (PowerSet)malloc( sizeof(struct powerSetStruct));
 
if (ps) {
ps->elements = (Set*)malloc( max*sizeof(Set));
ps->count = max;
ps->printer = PrintSet;
ps->nlAfterElements = 1;
 
for (ix=0; ix<max; ix++) {
int setsize = 0;
Set se = (Set)malloc(sizeof(struct setStruct));
 
for (j=0; j<set->count; j++)
if (ix & (1<<j)) setsize++;
if (setsize > 0) {
se->elements = (SetType *)malloc(setsize *sizeof(SetType));
n = 0;
for (j=0; j<set->count; j++) {
if (ix & (1<<j)) {
se->elements[n] = set->elements[j];
n++;
}
}
}
else {
printf("No elements in set %d\n", ix);
se->elements = NULL;
}
se->count = setsize;
se->printer = set->printer;
se->nlAfterElements = set->nlAfterElements;
ps->elements[ix] = se;
}
}
return ps;
}
 
void PrintSet( Set s)
{
char *sep = "";
int ix;
printf("{");
for (ix=0; ix<s->count; ix++) {
printf("%s ", sep);
s->printer(s->elements[ix]);
sep = (s->nlAfterElements)? ",\n " :",";
}
printf(" }");
}
 
void PrintString( char *str)
{
printf("%s", str);
}
 
int main(int argc, char *argv[])
{
char *eles[] = {"Red","Grn","Blu","Ylo"};
struct setStruct aSet = { 4, eles, PrintString, 0 };
PowerSet p = GetPowerSet( &aSet);
 
PrintSet(&aSet); printf("\n");
PrintSet( (Set)p ); printf("\n");
return 0;
}</lang>
Output:
<pre>{ Red, Grn, Blu, Ylo }
{ { },
{ Red },
{ Grn },
{ Red, Grn },
{ Blu },
{ Red, Blu },
{ Grn, Blu },
{ Red, Grn, Blu },
{ Ylo },
{ Red, Ylo },
{ Grn, Ylo },
{ Red, Grn, Ylo },
{ Blu, Ylo },
{ Red, Blu, Ylo },
{ Grn, Blu, Ylo },
{ Red, Grn, Blu, Ylo }}</pre>
 
=={{header|C++}}==