Given an array of length n, print all sub arrays of length r

#include <stdio.h>

/* Prints all the subarrays of length r */

/* @params: a, given array */
/* @params: n, a length */
/* @params: sub, sub array */
/* @params: r, sub length */
/* @params: i, current index of a */
/* @params: j, current index of sub */

void subarray(int a[], int n, int sub[], int r, int i, int j)
{
if(j == r) /* current index of sub r, print sub */
{
int k;

printf("( ");

for(k = 0; k < r; k++)
printf("%d ", sub[k]);

printf(")\n");
}
else
{
if(i < n)
{
sub[j] = a[i];

subarray(a, n, sub, r, i + 1, j + 1); /* Include current element */
subarray(a, n, sub, r, i + 1, j); /* Override the current element */
}
}

}

int main()
{
int n, r;

scanf("%d%d", &n, &r);

int a[n], sub[r];

int i;

for(i = 0 ; i < n; ++i)
scanf("%d", a + i);

subarray(a, n , sub, r, 0, 0);
}
Advertisements

2 thoughts on “Given an array of length n, print all sub arrays of length r

  1. Well in this we go through all the possible permutations i.e n!, for example if n = 60 and r = 59 then this solution is not feasible. but in reality number of sets are 60 which is quite small.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s