1

Print k-element subsets of an n element set (In essence n choose k) represent each subset as an array and skip B[0].

For example [0 1 0 1] means {1,3} to print. I believe my main problem is in my printSubsets() function because I am calling the method twice.

But it looks like it can't do that; it ignores the "2" in the index until the very end of the program.

Code

#include <stdio.h>
#include <stdlib.h>

void printSet(int B[], int n) {
    for(int j = 1; j <= n; j++) {
            printf("%d", B[j]);

    }
}

void printSubsets(int B[], int n, int k, int i) {
    if(i <= n) {
        if(k == 0) {
            printSet(B, n);
            printf("\n");
        }else{
            B[i] = 1; //print 1 in the index of interest and recurse
            printSubsets(B, n, k-1, i++);
            B[i] = 2; //print 2 as a holder to ignore that index
            printSubsets(B, n, k, i++);
        }
    }
}

int main(){
    int n;
    int k;
    scanf("%d %d", &n, &k);
    int B[101];
    printSubsets(B, n, k, 1);

    return EXIT_SUCCESS;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
jeuchi
  • 13
  • 5
  • just realized ++i actually moves the index instead of i++ – jeuchi Oct 04 '19 at 20:02
  • What maks you think so? If I get you right, then both "moves the index". – Yunnosch Oct 04 '19 at 21:53
  • I think what @jeuchi means is that ++i moves the index before returning it, while i++ moves the index AFTER returning it. – OrdoFlammae Oct 04 '19 at 22:05
  • Provide more info about program test input and desire output. – EsmaeelE Oct 04 '19 at 22:34
  • @EsmaeelE Basically I want the user to input 2 numbers (n and k) and the program will give all subsets of k-elements of the set size n. For example if the user enters "3 2". The program will give out {1,2} {1,3}, {2,3}. – jeuchi Oct 04 '19 at 22:38
  • I think this link may help you. https://www.geeksforgeeks.org/print-subsets-given-size-set/ – EsmaeelE Oct 04 '19 at 22:53
  • https://stackoverflow.com/questions/12548312/find-all-subsets-of-length-k-in-an-array – EsmaeelE Oct 04 '19 at 22:57
  • This link answer your question: https://codereview.stackexchange.com/questions/190747/find-subsets-of-size-k-in-n-set – EsmaeelE Oct 07 '19 at 11:29

0 Answers0