{"id":25979,"date":"2017-10-26T09:21:48","date_gmt":"2017-10-26T03:51:48","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25979"},"modified":"2017-10-26T09:21:48","modified_gmt":"2017-10-26T03:51:48","slug":"c-programming-print-possible-combinations-r-elements-given-array-size-n","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-programming-print-possible-combinations-r-elements-given-array-size-n\/","title":{"rendered":"C++ Programming &#8211; Print all possible combinations of r elements in a given array of size n"},"content":{"rendered":"<p>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}.<span id=\"more-118604\"><\/span><\/p>\n<p>Following are two methods to do this.<\/p>\n<p><strong>Method 1 (Fix Elements and Recur)<\/strong><br \/>\nWe create a temporary array \u2018data[]\u2019 which stores all outputs one by one. The idea is to start from first index (index = 0) in data[], one by one fix elements at this index and recur for remaining indexes. Let the input array be {1, 2, 3, 4, 5} and r be 3. We first fix 1 at index 0 in data[], then recur for remaining indexes, then we fix 2 at index 0 and recur. Finally, we fix 3 and recur for remaining indexes. When number of elements in data[] becomes equal to r (size of a combination), we print data[].<\/p>\n<p>Following diagram shows recursion tree for same input.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-25987\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/combination.png\" alt=\"Combination\" width=\"908\" height=\"359\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/combination.png 908w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/combination-300x119.png 300w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/combination-768x304.png 768w\" sizes=\"(max-width: 908px) 100vw, 908px\" \/><br \/>\nFollowing is C++ implementation of above approach.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C++ Program<\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ Program to print all combination of size r in an array of size n<br\/>#include &lt;stdio.h&gt;<br\/>void combinationUtil(int arr[], int data[], int start, int end, <br\/>                     int index, int r);<br\/> <br\/>\/\/ The main function that prints all combinations of size r<br\/>\/\/ in arr[] of size n. This function mainly uses combinationUtil()<br\/>void printCombination(int arr[], int n, int r)<br\/>{<br\/>    \/\/ A temporary array to store all combination one by one<br\/>    int data[r];<br\/> <br\/>    \/\/ Print all combination using temprary array &#039;data[]&#039;<br\/>    combinationUtil(arr, data, 0, n-1, 0, r);<br\/>}<br\/> <br\/>\/* arr[]  ---&gt; Input Array<br\/>   data[] ---&gt; Temporary array to store current combination<br\/>   start &amp; end ---&gt; Staring and Ending indexes in arr[]<br\/>   index  ---&gt; Current index in data[]<br\/>   r ---&gt; Size of a combination to be printed *\/<br\/>void combinationUtil(int arr[], int data[], int start, int end,<br\/>                     int index, int r)<br\/>{<br\/>    \/\/ Current combination is ready to be printed, print it<br\/>    if (index == r)<br\/>    {<br\/>        for (int j=0; j&lt;r; j++)<br\/>            printf(&quot;%d &quot;, data[j]);<br\/>        printf(&quot;\\n&quot;);<br\/>        return;<br\/>    }<br\/> <br\/>    \/\/ replace index with all possible elements. The condition<br\/>    \/\/ &quot;end-i+1 &gt;= r-index&quot; makes sure that including one element<br\/>    \/\/ at index will make a combination with remaining elements<br\/>    \/\/ at remaining positions<br\/>    for (int i=start; i&lt;=end &amp;&amp; end-i+1 &gt;= r-index; i++)<br\/>    {<br\/>        data[index] = arr[i];<br\/>        combinationUtil(arr, data, i+1, end, index+1, r);<br\/>    }<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    int arr[] = {1, 2, 3, 4, 5};<br\/>    int r = 3;<br\/>    int n = sizeof(arr)\/sizeof(arr[0]);<br\/>    printCombination(arr, n, r);<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>1 2 3\r\n1 2 4\r\n1 2 5\r\n1 3 4\r\n1 3 5\r\n1 4 5\r\n2 3 4\r\n2 3 5\r\n2 4 5\r\n3 4 5<\/pre>\n<p><em>How to handle duplicates?<\/em><br \/>\nNote that the above method doesn\u2019t handle duplicates. For example, if input array is {1, 2, 1} and r is 2, then the program prints {1, 2} and {2, 1} as two different combinations. We can avoid duplicates by adding following two additional things to above code.<br \/>\n1) Add code to sort the array before calling combinationUtil() in printCombination()<br \/>\n2) Add following lines at the end of for loop in combinationUtil()<\/p>\n<pre>        \/\/ Since the elements are sorted, all occurrences of an element\r\n        \/\/ must be together\r\n        while (arr[i] == arr[i+1])\r\n             i++;<\/pre>\n<p>See <strong><a href=\"http:\/\/ideone.com\/ywsqBz\" target=\"_blank\" rel=\"noopener noreferrer\">this <\/a><\/strong>for an implementation that handles duplicates.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 2 (Include and Exclude every element)<\/strong><br \/>\nLike the above method, We create a temporary array data[]. The idea here is similar to <a href=\"http:\/\/www.geeksforgeeks.org\/dynamic-programming-subset-sum-problem\/\" target=\"_blank\" rel=\"noopener\">Subset Sum Problem<\/a>. We one by one consider every element of input array, and recur for two cases:<\/p>\n<p>1) The element is included in current combination (We put the element in data[] and increment next available index in data[])<br \/>\n2) The element is excluded in current combination (We do not put the element and do not change index)<\/p>\n<p>When number of elements in data[] become equal to r (size of a combination), we print it.<\/p>\n<p>This method is mainly based on <a href=\"http:\/\/en.wikipedia.org\/wiki\/Pascal&#039;s_rule\" target=\"_blank\" rel=\"noopener\">Pascal\u2019s Identity<\/a>, i.e. <strong>n<sub>c<\/sub><sub>r<\/sub> = n-1<sub>c<\/sub><sub>r<\/sub> + n-1<sub>c<\/sub><sub>r-1<\/sub><\/strong><\/p>\n<p>Following is C++ implementation of method 2.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C Program<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ Program to print all combination of size r in an array of size n<br\/>#include&lt;stdio.h&gt;<br\/>void combinationUtil(int arr[],int n,int r,int index,int data[],int i);<br\/> <br\/>\/\/ The main function that prints all combinations of size r<br\/>\/\/ in arr[] of size n. This function mainly uses combinationUtil()<br\/>void printCombination(int arr[], int n, int r)<br\/>{<br\/>    \/\/ A temporary array to store all combination one by one<br\/>    int data[r];<br\/> <br\/>    \/\/ Print all combination using temprary array &#039;data[]&#039;<br\/>    combinationUtil(arr, n, r, 0, data, 0);<br\/>}<br\/> <br\/>\/* arr[]  ---&gt; Input Array<br\/>   n      ---&gt; Size of input array<br\/>   r      ---&gt; Size of a combination to be printed<br\/>   index  ---&gt; Current index in data[]<br\/>   data[] ---&gt; Temporary array to store current combination<br\/>   i      ---&gt; index of current element in arr[]     *\/<br\/>void combinationUtil(int arr[], int n, int r, int index, int data[], int i)<br\/>{<br\/>    \/\/ Current cobination is ready, print it<br\/>    if (index == r)<br\/>    {<br\/>        for (int j=0; j&lt;r; j++)<br\/>            printf(&quot;%d &quot;,data[j]);<br\/>        printf(&quot;\\n&quot;);<br\/>        return;<br\/>    }<br\/> <br\/>    \/\/ When no more elements are there to put in data[]<br\/>    if (i &gt;= n)<br\/>        return;<br\/> <br\/>    \/\/ current is included, put next at next location<br\/>    data[index] = arr[i];<br\/>    combinationUtil(arr, n, r, index+1, data, i+1);<br\/> <br\/>    \/\/ current is excluded, replace it with next (Note that<br\/>    \/\/ i+1 is passed, but index is not changed)<br\/>    combinationUtil(arr, n, r, index, data, i+1);<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    int arr[] = {1, 2, 3, 4, 5};<br\/>    int r = 3;<br\/>    int n = sizeof(arr)\/sizeof(arr[0]);<br\/>    printCombination(arr, n, r);<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>1 2 3\r\n1 2 4\r\n1 2 5\r\n1 3 4\r\n1 3 5\r\n1 4 5\r\n2 3 4\r\n2 3 5\r\n2 4 5\r\n3 4 5<\/pre>\n<p><em>How to handle duplicates in method 2?<\/em><br \/>\nLike method 1, we can following two things to handle duplicates.<br \/>\n1) Add code to sort the array before calling combinationUtil() in printCombination()<br \/>\n2) Add following lines between two recursive calls of combinationUtil() in combinationUtil()<\/p>\n<pre>        \/\/ Since the elements are sorted, all occurrences of an element\r\n        \/\/ must be together\r\n        while (arr[i] == arr[i+1])\r\n             i++;<\/pre>\n<p>See <strong><a href=\"http:\/\/ideone.com\/91MYjB\" target=\"_blank\" rel=\"noopener noreferrer\">this <\/a><\/strong>for an implementation that handles duplicates.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>C++ Programming &#8211; Print all possible combinations of r elements in a given array of size n &#8211; Mathematical Algorithms &#8211; Given an array of size n, and r is 2.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,83515,1,74058],"tags":[73383,74845,76423,76413,76420,76418,74851,76432,76419,76429,70851,76427,74847,73721,75062,72067,72058,70047,76434,70832,76426,70811,70824,76424,76425,76430,76428,70822,74260,76421,75074,70838,76431,76422,76417,70323,70331,70328,73693,70384,70347,76433,76414,70808,74081,76415,70830,76416,70810,70836],"class_list":["post-25979","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-c-programming-3","category-coding","category-mathematical-algorithms","tag-alphabet-pattern-programs-in-c","tag-basic-c-program-examples","tag-basic-c-programs","tag-basic-c-programs-asked-in-interview","tag-basic-c-programs-for-beginners","tag-basic-c-programs-for-interviews","tag-basic-programs-in-c","tag-c-basic-programs","tag-c-code-examples","tag-c-interview-programs","tag-c-language-examples","tag-c-language-programs-examples","tag-c-progra","tag-c-program-for-permutation-of-numbers","tag-c-program-to-count-number-of-words-in-a-string","tag-c-program-to-print-patterns-of-numbers","tag-c-program-to-print-patterns-of-numbers-and-alphabets","tag-c-programming","tag-c-programming-basics","tag-c-programming-codes","tag-c-programming-com","tag-c-programming-examples","tag-c-programming-examples-with-output","tag-c-programming-language-examples","tag-c-programming-programs","tag-c-programs-asked-in-interview","tag-c-programs-for-interview","tag-c-programs-with-output","tag-combination-math","tag-cs-language-code","tag-example-c-program","tag-example-of-c-program","tag-interview-programs-in-c","tag-ncr-in-maths","tag-outcome-possibilities-calculator","tag-permutation-and-combination","tag-permutation-and-combination-formula","tag-permutation-formula","tag-permutation-of-string","tag-permutation-program-in-c","tag-permutations-and-combinations-formula","tag-program-in-c","tag-programming-examples","tag-programming-in-c","tag-programming-interview-questions","tag-sample-c-code","tag-sample-c-program","tag-sample-programs-in-c","tag-simple-c-programs","tag-simple-c-programs-with-output"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25979","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25979"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25979\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25979"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25979"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25979"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}