Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<ol> <li>Sort the array.</li> <li>Use a nested loop where the outer loop iterates through each element in the array. If the next element has the same value as the last, skip. The inner loop then places that element at each position in the list. Saving a permutation on each loop.</li> </ol> <p>This will generate the permutations as well as skip repetitious permutations.</p> <pre><code>int[] sortedSourceArray = ...; int last = -1; int current = -1; // build one permutation with the original array buildPermutation(permutationList, sortedSourceArray); // I'm not going to implement this for you. for (int i = 0; i &lt; sortedSourceArray.length; i++) { current = sortedSourceArray[i]; // check if the new value is the same as the last if(current == last) continue; // remove the current element from the list // build your permutations for(int j = 0; j &lt; sortedSourceArray.length; j++) { // skip if its inserting the element at its original position if(j == i) continue; // fix the duplicates for blocks of repeated elements if(j &lt; sortedSourceArray.length-1 &amp;&amp; sortedSourceArray[j+1] == current) continue; // inject the current element at the new position inject(sortedSourceArray, current, j); // build the permutation buildPermutation(permutationList, sortedSourceArray); // remove the current element from that position remove(sortedSourceArray, j); } last = current; } </code></pre> <p>EDIT: Actually I think this would need to be tweaked a bit more to capture the last few cases where duplicates are generated. That would be where a repeated element is inserted next to its same value. I've changed the code appropriately.</p>
 

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