Friday, 7 June 2019

Print all possible combinations of r elements in a given array of size n

Using exclude and include


#include <stdio.h>
int a[100],temp[100],n,r;
void fun(int index, int i)
{
    if (index == r)
    {
        for (int j = 0; j < r; j++)
            printf("%d", temp[j]);
        printf("\n");
        return;
    }

    if (i >= n)
        return;

    temp[index] = a[i];       
   
    fun(index + 1, i + 1);     //current element is included

    fun(index,i+1);              // current element is excluded, replace it with next element

}
int main()
{
    int i;
    printf("enter the number of elements\n");
    scanf("%d",&n);
    printf("enter the array elements");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("\n enter the number of digits");
    scanf("%d",&r);
    int temp[r];
    fun(0,0);
}

  =============================================================
#include <stdio.h>
int a[100],temp[100],n,r;
void fun(int start, int end, int index)
{
    if (index == r)
    {
        for (int j = 0; j < r; j++)
            printf("%d", temp[j]);
        printf("\n");
        return;
    }

    for (int i = start; i <= end && end - i + 1 >= r - index; i++)
    {
        temp[index] = a[i];
        fun(i+1,end, index+1);
    } 
}
int main()
{
    int i;
    printf("enter the number of elements\n");
    scanf("%d",&n);
    printf("enter the array elements");
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    printf("\n enter the number of digits");
    scanf("%d",&r);
    int temp[r];
    fun(0,n-1,0);
}



1 comment:

  1. Thank you for the diagram mam, it helped me to understand the program.

    ReplyDelete