{"id":25980,"date":"2017-10-26T09:23:20","date_gmt":"2017-10-26T03:53:20","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25980"},"modified":"2017-10-26T09:23:20","modified_gmt":"2017-10-26T03:53:20","slug":"java-programming-print-possible-combinations-r-elements-given-array-size-n","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-print-possible-combinations-r-elements-given-array-size-n\/","title":{"rendered":"Java 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 java\" 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\" \/><\/p>\n<p>Following is java implementation of above approach.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java Program<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to print all combination of size r in an array of size n<br\/>import java.io.*;<br\/> <br\/>class Permutation {<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\/>    static void combinationUtil(int arr[], int data[], int start,<br\/>                                int end, 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\/>                System.out.print(data[j]+&quot; &quot;);<br\/>            System.out.println(&quot;&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\/>    \/\/ The main function that prints all combinations of size r<br\/>    \/\/ in arr[] of size n. This function mainly uses combinationUtil()<br\/>    static void printCombination(int arr[], int n, int r)<br\/>    {<br\/>        \/\/ A temporary array to store all combination one by one<br\/>        int data[]=new int[r];<br\/> <br\/>        \/\/ Print all combination using temprary array &#039;data[]&#039;<br\/>        combinationUtil(arr, data, 0, n-1, 0, r);<br\/>    }<br\/> <br\/>    \/*Driver function to check for above function*\/<br\/>    public static void main (String[] args) {<br\/>        int arr[] = {1, 2, 3, 4, 5};<br\/>        int r = 3;<br\/>        int n = arr.length;<br\/>        printCombination(arr, n, r);<br\/>    }<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 Java implementation of method 2.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java Program<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to print all combination of size r in an array of size n<br\/>import java.io.*;<br\/> <br\/>class Permutation {<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\/>    static void combinationUtil(int arr[], int n, int r, int index,<br\/>                                int data[], int i)<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\/>                System.out.print(data[j]+&quot; &quot;);<br\/>            System.out.println(&quot;&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\/>    \/\/ The main function that prints all combinations of size r<br\/>    \/\/ in arr[] of size n. This function mainly uses combinationUtil()<br\/>    static void printCombination(int arr[], int n, int r)<br\/>    {<br\/>        \/\/ A temporary array to store all combination one by one<br\/>        int data[]=new int[r];<br\/> <br\/>        \/\/ Print all combination using temprary array &#039;data[]&#039;<br\/>        combinationUtil(arr, n, r, 0, data, 0);<br\/>    }<br\/> <br\/>    \/*Driver function to check for above function*\/<br\/>    public static void main (String[] args) {<br\/>        int arr[] = {1, 2, 3, 4, 5};<br\/>        int r = 3;<br\/>        int n = arr.length;<br\/>        printCombination(arr, n, r);<br\/>    }<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","protected":false},"excerpt":{"rendered":"<p>Java 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":[1,2139,74058],"tags":[76509,76496,74639,75765,76487,76489,76505,76501,73721,76503,74268,76504,74252,76497,74251,76510,76498,76493,76492,76486,76511,74234,76514,76488,74238,75239,74247,76494,2947,76490,76500,76499,76483,76495,76484,74246,73693,76508,76329,75254,76512,76502,76485,74248,74250,76491,76513,75249,76507,76506],"class_list":["post-25980","post","type-post","status-publish","format-standard","hentry","category-coding","category-java","category-mathematical-algorithms","tag-4-digit-number-combinations","tag-4r-size","tag-all-combinations-of-4-numbers","tag-all-possible-combinations-of-4-numbers","tag-basic-java-programs","tag-basic-programs-in-java","tag-c-program-for-combination-of-3-numbers","tag-c-program-for-combination-of-n-numbers","tag-c-program-for-permutation-of-numbers","tag-c-program-to-find-combination-of-numbers","tag-combination-of-numbers","tag-combinations-in-c","tag-combinations-java","tag-fibonacci-sequence-list","tag-find-all-permutations-of-a-string-java","tag-find-combinations-of-numbers","tag-find-possible-combinations","tag-finding-all-possible-combinations-of-numbers","tag-for-loop-example-in-java","tag-how-to-print-array","tag-how-to-print-array-in-java","tag-java-combinations","tag-java-exercises-with-solutions","tag-java-pattern-programs","tag-java-permutation-algorithm","tag-java-program-to-find-prime-number","tag-java-program-to-print-all-possible-combinations-of-a-number","tag-java-program-to-print-pattern-of-alphabets","tag-java-random-number-between-0-and-1","tag-java-simple-program","tag-list-all-possible-combinations","tag-number-combinations","tag-number-pattern-programs-in-java","tag-number-patterns-in-java","tag-pattern-programs-in-java","tag-permutation-of-numbers-in-java","tag-permutation-of-string","tag-possible-combinations-of-4-numbers","tag-prime-number-program-in-java-print-1-to-100","tag-prime-numbers-from-1-to-100-in-java","tag-print-array-in-java","tag-print-combinations","tag-print-r","tag-program-to-find-combinations-of-numbers-in-java","tag-string-programs-in-java-for-interview","tag-substring-java-example","tag-sum-of-two-numbers-in-java","tag-write-a-java-program-to-check-prime-number","tag-write-a-program-in-java-to-print-the-following-pattern","tag-write-a-program-to-print-the-given-pattern"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25980","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=25980"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25980\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25980"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25980"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25980"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}