fork(110) download
  1. // Program to print all combination of size r in an array of size n
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. void combinationUtil(int arr[], int n, int r, int count, int data[], int i);
  5.  
  6. // Needed for qsort. See http://w...content-available-to-author-only...s.com/reference/cstdlib/qsort/
  7. int compare (const void * a, const void * b)
  8. {
  9. return ( *(int*)a - *(int*)b );
  10. }
  11.  
  12. // The main function that prints all combinations of size r
  13. // in arr[] of size n. This function mainly uses combinationUtil()
  14. void printCombination(int arr[], int n, int r)
  15. {
  16. // A temporary array to store all combination one by one
  17. int data[r];
  18.  
  19. // Sort array to handle duplicates
  20. qsort (arr, n, sizeof(int), compare);
  21.  
  22. // Print all combination using temprary array 'data[]'
  23. combinationUtil(arr, n, r, 0, data, 0);
  24. }
  25.  
  26. /* arr[] ---> Input Array
  27.   n ---> Size of input array
  28.   r ---> Size of a combination to be printed
  29.   index ---> Current index in data[]
  30.   data[] ---> Temporary array to store current combination
  31.   i ---> index of current element in arr[] */
  32. void combinationUtil(int arr[], int n, int r, int index, int data[], int i)
  33. {
  34. // Current cobination is ready, print it
  35. if (index == r)
  36. {
  37. for (int j=0; j<r; j++)
  38. printf("%d ",data[j]);
  39. printf("\n");
  40. return;
  41. }
  42.  
  43. // When no more elements are there to be put
  44. if (i >= n)
  45. return;
  46.  
  47. // current is included, put next at next location
  48. data[index] = arr[i];
  49. combinationUtil(arr, n, r, index+1, data, i+1);
  50.  
  51. // Remove duplicates
  52. while (arr[i] == arr[i+1])
  53. i++;
  54.  
  55. // current is excluded, replace it with next (Note that
  56. // i+1 is passed, but index is not changed)
  57. combinationUtil(arr, n, r, index, data, i+1);
  58. }
  59.  
  60. // Driver program to test above functions
  61. int main()
  62. {
  63. int arr[] = {1, 2, 1, 3, 1};
  64. int r = 3;
  65. int n = sizeof(arr)/sizeof(arr[0]);
  66. printCombination(arr, n, r);
  67. return 0;
  68. }
Success #stdin #stdout 0s 2852KB
stdin
Standard input is empty
stdout
1 1 1 
1 1 2 
1 1 3 
1 2 3