Note that there are some explanatory texts on larger screens.

plurals
  1. POCombinations of positive integers uniq (order not important)
    primarykey
    data
    text
    <p>So, I was searching for a good solution for my problem.</p> <p>I need to generate(print) all the combination of a list of integers, for example: if the array contain integers from 0 to n-1, where n = 5:</p> <pre><code>int array[] = {0,1,2,3,4}; </code></pre> <p>the order of integers in the combination are NOT important, meaning {1,1,3}, {1,3,1} and {3,1,1} are actually the same combination because they all contain one 3 and two ones.</p> <p>so for the above array, all combination of length 3:</p> <pre><code>0,0,0 -&gt; the 1st combination 0,0,1 0,0,2 0,0,3 0,0,4 0,1,1 -&gt; this combination is 0,1,1, not 0,1,0 because we already have 0,0,1. 0,1,2 0,1,3 0,1,4 0,2,2 -&gt; this combination is 0,2,2, not 0,2,0 because we already have 0,0,2. 0,2,3 . . 0,4,4 1,1,1 -&gt; this combination is 1,1,1, not 1,0,0 because we already have 0,0,1. 1,1,2 1,1,3 1,1,4 1,2,2 -&gt; this combination is 1,2,2, not 1,2,0 because we already have 0,1,2. . . 4,4,4 -&gt; Last combination </code></pre> <p>For Now I Wrote Code for doing this, but my problem is: if the numbers in the array are not integer from 0 to n-1, lets say if the array was like this</p> <pre><code>int array[] = {1,3,6,7}; </code></pre> <p>my code doesn't work on this case, any algorithm or code for solving this problem,,</p> <p>Here is my code :</p> <pre><code>unsigned int next_combination(unsigned int *ar, int n, unsigned int k){ unsigned int finished = 0; unsigned int changed = 0; unsigned int i; for (i = k - 1; !finished &amp;&amp; !changed; i--) { if (ar[i] &lt; n - 1) { /* Increment this element */ ar[i]++; if (i &lt; k - 1) { /* Make the elements after it the same */ unsigned int j; for (j = i + 1; j &lt; k; j++) { ar[j] = ar[j - 1]; } } changed = 1; } finished = i == 0; } if (!changed) { /* Reset to first combination */ for (i = 0; i &lt; k; i++){ ar[i] = 0; } } return changed; } </code></pre> <p>And this is the main:</p> <pre><code>int main(){ unsigned int numbers[] = {0, 0, 0, 0, 0}; const unsigned int k = 3; unsigned int n = 5; do{ for(int i=0 ; i&lt;k ; ++i) cout &lt;&lt; numbers[i] &lt;&lt; " "; cout &lt;&lt; endl; }while (next_combination(numbers, n, k)); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload