3 Replies - 464 Views - Last Post: 04 December 2017 - 11:01 AM Rate Topic: -----

#1 a940377  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 24-November 17

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

Posted 04 December 2017 - 07:59 AM

Given an array of size n, generate and print all possible combinations of r elements in array. For example, if input array is {1, 2, 3, 4} and r is 2, then output should be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4} and {3, 4}.

These are what i am thinking about:

#include<stdio.h>
#include<stdlib.h>
int cover(int a[],int n,int k)
{
  int i;
  if(n==n-k-1)
  {
    for(i=0;i<n;i++)
    {
      if(i!=n-k-1)
        printf("%d ",a[i]);
    }
    printf("\n");
    return 0;
  }
  else
    cover(a,n+1,k);
}
int com(int a[],int n,int k)
{
  if(k==n-1)
  {
    cover(a,n,k);
    return 0;
  }
  else
    com(a,n,k+1);

}
void main(int argc,char *argv[])
{
  int a[1000],i,n,k;
  FILE *output;
  output=fopen("output","w");
  n=atoi(argv[1]);
  k=atoi(argv[2]);
  for(i=0;i<n;i++)
  scanf("%d",&a[i]);
  com(a,n,k);
}



Is This A Good Question/Topic? 0
  • +

Replies To: Print all possible combinations of r elements in a given array of size

#2 snoopy11  Icon User is online

  • Engineering ● Software
  • member icon

Reputation: 1456
  • View blog
  • Posts: 4,715
  • Joined: 20-March 10

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

Posted 04 December 2017 - 08:11 AM

Reading this might be helpful...

https://www.mathplan...nd-combinations
Was This Post Helpful? 0
  • +
  • -

#3 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 6112
  • View blog
  • Posts: 21,040
  • Joined: 05-May 12

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

Posted 04 December 2017 - 10:06 AM

Ah, but the OP is not looking for the count of combinations, but rather actually needs to enumerate all the combinations.
Was This Post Helpful? 0
  • +
  • -

#4 snoopy11  Icon User is online

  • Engineering ● Software
  • member icon

Reputation: 1456
  • View blog
  • Posts: 4,715
  • Joined: 20-March 10

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

Posted 04 December 2017 - 11:01 AM

A permutation then .... ??
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1