1

This is a program to store all possible combinations of given array in the array ans[][].

#include <stdio.h>

int ingredients = 10;
int ans[10][10];
int x = 0;

void makeCombination(int arr1[], int data[], int st, int end, int index, int r);

void CombinationDisplay(int arr1[], int n, int r) {
    int data[r];
    makeCombination(arr1, data, 0, n - 1, 0, r);
}

void makeCombination(int arr1[], int data[], int st, int end, int index, int r) {
    if (index == r) {
        for (int j = 0; j < r; j++)
            ans[x][j] = data[j];
        x++;
        return;
    }
    for (int i = st; i <= end && end - i + 1 >= r - index; i++) {
        data[index] = arr1[i];
        makeCombination(arr1, data, i + 1, end, index + 1, r);
    }
}

int main() {
    int arr1[ingredients], i;

    for (i = 0; i < ingredients; i++)
        arr1[i] = i;
    int n = sizeof(arr1) / sizeof(arr1[0]);

    for (int r = 0; r < ingredients; r++)
        CombinationDisplay(arr1, n, r);
    
    for (i = 0; i < ingredients; i++) {
        for (int j = 0; j < i; j++) {
            printf("%d", ans[i][j]);
        }
        printf("\n");
    }
    return 0;
}

It should store all the combinations in an array ans and print it. However, it does not show any errors, nor output in the terminal.

14
  • When I run your program I get some output... Commented Feb 6, 2022 at 6:01
  • like 0000000000.... infinitely? Commented Feb 6, 2022 at 6:04
  • no. I get stuff like: 0 01 012 0123 01235 012456 0134567 02345678 123456789 Commented Feb 6, 2022 at 6:06
  • thats the correct output! so i have problem in my compiler? Commented Feb 6, 2022 at 6:07
  • It can also be that the program has undefined behavior. What output would you expect for int ingredients = 2; ? Commented Feb 6, 2022 at 6:11

1 Answer 1

1

There are multiple problems in your code:

  • int ans[10][10]; is not large enough for all combinations of 10 elements: there are 210 possible combinations (subsets of a set of 10 elements).
  • printing initial subsets of subsets would produce many duplicates.
  • a recursive approach is not as simple as an iterative approach for this problem.

Here is a modified version:

#include <stdio.h>

#define INGREDIENTS 10  // must be in the range 1 to 30 for 32-bit int

int main() {
    for (int i = 0; i < (1 << INGREDIENTS); i++) {
        for (int j = 0; j < INGREDIENTS; j++) {
            if (i & (1 << j))
                printf("%u ", j);
        }
        printf("\n");
    }
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.