ulvis.paste.net

Paste Search Dynamic
Recent pastes
Combination Repetition
  1. #include <stdio.h>
  2.  
  3. // C program to print all combination of size r in an array
  4. // of size n with repetitions allowed
  5.  
  6. /* arr[]  ---> Input Array
  7.   chosen[] ---> Temporary array to store indices of
  8.                    current combination
  9.    start & end ---> Staring and Ending indexes in arr[]
  10.    r ---> Size of a combination to be printed */
  11. void CombinationRepetitionUtil(int chosen[], int arr[],
  12.                     int index, int r, int start, int end)
  13. {
  14.     // Since index has become r, current combination is
  15.     // ready to be printed, print
  16.     if (index == r)
  17.     {
  18.         for (int i = 0; i < r; i++)
  19.             printf("%d ", arr[chosen[i]]);
  20.         printf("\n");
  21.         return;
  22.     }
  23.  
  24.     // One by one choose all elements (without considering
  25.     // the fact whether element is already chosen or not)
  26.     // and recur
  27.     for (int i = start; i <= end; i++)
  28.     {
  29.         chosen[index] = i;
  30.         CombinationRepetitionUtil(chosen, arr, index + 1,
  31.                                                r, i, end);
  32.     }
  33.     return;
  34. }
  35.  
  36. // The main function that prints all combinations of size r
  37. // in arr[] of size n with repitions. This function mainly
  38. // uses CombinationRepetitionUtil()
  39. void CombinationRepetition(int arr[], int n, int r)
  40. {
  41.     // Allocate memory
  42.     int chosen[r+1];
  43.  
  44.     // Call the recursice function
  45.     CombinationRepetitionUtil(chosen, arr, 0, r, 0, n-1);
  46. }
  47.  
  48. // Driver program to test above functions
  49. int main(void)
  50. {
  51.     int arr[] = {1, 2, 3};
  52.     int n = sizeof(arr)/sizeof(arr[0]);
  53.     int r = 4;
  54.     CombinationRepetition(arr, n, r);
  55.     return 0;
  56. }
Parsed in 0.011 seconds