-1

I am working on an assignment and i made a function to get the power set and it worked but if the set like this:

{1,2,3}

it print out this :

{{},{1,},{2,},{1,2,},{3},{1,3},{2,3},{1,2,3}}

and i can't remove these commas to become like that:

{{},{1},{2},{1,2},{3},{1,3},{2,3},{1,2,3}}

Source code for this function:

void power_set(int set1[], int set1_length) {
    int power = pow(2,set1_length);

    cout << "{";
    for (int i = 0; i < power; i++) {
        cout << "{";
        for (int j = 0; j < set1_length; j++ ) {
            if(i & (1<<j)) {
                cout << set1[j];
                if (j < set1_length - 1) cout << ",";
            }
        }
        cout << "}";
        if (i != power - 1)cout << ",";
    }
    cout << "}";
}

2 Answers2

0

One way to solve this is to keep track of whether you've printed the first number in a set. Instead of:

for (int j = 0; j < set1_length; j++ ) {
    if(i & (1<<j)) {
        cout << set1[j];
        if (j < set1_length - 1) cout << ",";
    }
}

You could use a flag to only print a comma starting from the second number in a set:

bool first = true;
for (int j = 0; j < set1_length; j++ ) {
    if(i & (1<<j)) {
        if (first) {first = false;}
        else {cout << ",";}
        cout << set1[j];
    }
}
frslm
  • 2,975
  • 3
  • 11
  • 25
-1

Check your if statement:

if (j < set1_length && (i & (1 << (j+1)))) cout << ",";
Ajris
  • 570
  • 6
  • 25