Monday, 15 July 2013

[C Programming #3] Print all combinations of given array with given size

Problem: Print all possible combinations of given array with given combination size limit.

Input:
array: 10 11 12 13 14
combination size: 3

Output:
10 11 12
10 12 13
10 13 14
11 12 13
11 13 14
12 13 14

Program:


  1. #include<stdio.h>

  2. void print_combinations(int a[], int n, int r) {
  3. int i,j,k;
  4. for (i = 0; i <= n-r; i++) {
  5. for (j = i+1; j+r-1 <= n; j++) {
  6. printf("%d\t", a[i]);
  7. for (k = 0; k < r-1; k++)
  8. printf("%d\t", a[j+k]);
  9. printf("\n");
  10. }
  11. printf("\n");
  12. }
  13. }

  14. int main()
  15. {
  16.   int a[] ={10,11,12,13,14};
  17.   int n=sizeof(a)/sizeof(a[0]);
  18.   print_combinations(a, n, 3);
  19.  
  20. return 0;
  21. }

No comments:

Post a Comment

You might also like

Related Posts Plugin for WordPress, Blogger...