Question
Write a C function that generates all the possible combinations of a set of items of a given size. It should have the following signature:
Write a C function that generates all the possible combinations of a set of items of a given size. It should have the following signature:
int** get_combs(int* items, int k, int len).
items: an array containing the given numbers
k: length of each combination
len: amount of numbers in items
This function should generate all possible combinations of items taken k at a time and return a 2-D array where each row contains one combination.
1. The combinations should be added to the 2-D array in their natural order
2. This 2-D array should be dynamically allocated in get_combs.
3. You will probably need to develop a helper function that actually computes the combinations.
4. Write the helper function recursively.
Use this code snippet (num_combs) to allocate space for the array:
int max(int a, int b){ return a > b ? a : b; }
int min(int a, int b){ return a < b ? a : b; }
int num_combs(int n, int k){ int combs = 1; int i;
for(i = n; i > max(k, n-k); i--){ combs *= i; }
for(i = 2; i <= min(k, n - k); i++){ combs /= i; } return combs;
}
The 2-D array will be used to print out the combinations.
Example :
How many items do you have: 5
Enter your items: 1 2 3 4 5
Enter k: 3
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started