I have the following program: \"\"\" #include<stdio.h> #include<stdlib.h> int nu
ID: 3818640 • Letter: I
Question
I have the following program:
"""
#include<stdio.h>
#include<stdlib.h>
int num_combs(int arr[], int data[], int start, int end,int index, int r){
if (index == r)
{
int j;
for (j=0; j<r; j++)
printf("%d ", data[j]);
printf(" ");
return;
}
int i;
for (i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
num_combs(arr, data, i+1, end, index+1, r);
}
}
int main(){
int i,j,k,n;
printf("How many items do you have: ");
scanf("%d",&n);
int *arr=(int *)malloc(sizeof(int)*n);
printf("Enter your items: ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("Enter k: ");
scanf("%d",&k);
int *temp=(int *)malloc(sizeof(int)*k);
num_combs(arr,temp,0,n-1,0,k);
return 0;
}
"""
Say I have an 2-dimensional array of known size named combs. How would I place each of the combinations into it?
For 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
I want combs[0][0] = 1 --> combs[9][2] = 5. How do I index combs properly? Instead of printing the data[j], I want to put data[j] in combs[x][y] but I don't know what x and y are.. Many thanks!
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
int num_combs(int arr[], int data[], int start, int end,int index, int r)
{
int x=0;
int combs[10][10];
if (index == r)
{
int j;
for (j=0; j<r; j++)
{
combs[index][j]=data[j];
printf("%d ", combs[index][j]);
}
printf(" ");
return;
}
int i;
for (i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
num_combs(arr, data, i+1, end, index+1, r);
}
}
int main()
{
int i,j,k,n;
printf("How many items do you have: ");
scanf("%d",&n);
int *arr=(int *)malloc(sizeof(int)*n);
printf("Enter your items: ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("Enter k: ");
scanf("%d",&k);
int *temp=(int *)malloc(sizeof(int)*k);
num_combs(arr,temp,0,n-1,0,k);
return 0;
}
--------------------------------
In combs[x][y], x= index and y=k;
--------------------------
output sample:-
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
---------------------------------------------------------------------------------------------
If you have any query, please feel free to ask.
Thanks a lot.