-
-
Save ayago/654cc811a2d80035eabf68d17694a751 to your computer and use it in GitHub Desktop.
Brute force printing of all permutations of a given array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private List<int[]> allPermutationsOf(int [] givenArray){ | |
| Queue<int[]> results = new LinkedList<>(); | |
| results.add(givenArray); | |
| int previousExpectedOutcome = 1; | |
| for(int pivot = 0; pivot < givenArray.length - 1; pivot++){ | |
| int expectedOutcomeForEachResult = givenArray.length - pivot; | |
| for(int c = 0; c < previousExpectedOutcome; c++){ | |
| int[] array = results.poll(); | |
| for(int outcome = 0; outcome < expectedOutcomeForEachResult; outcome++){ | |
| if(outcome == 0){ | |
| results.add(array); | |
| } else { | |
| int[] newOutcome = new int[givenArray.length]; | |
| for(int i = 0; i < pivot; i++){ | |
| newOutcome[i] = array[i]; | |
| } | |
| int pivotValue = array[pivot]; | |
| int shiftedIndex = pivot + outcome; | |
| int swapValue = array[shiftedIndex]; | |
| newOutcome[pivot] = swapValue; | |
| newOutcome[pivot + 1] = pivotValue; | |
| for(int i = pivot + 2; i <= shiftedIndex; i++){ | |
| newOutcome[i] = array[i - 1]; | |
| } | |
| for(int i = shiftedIndex + 1; i < givenArray.length; i++){ | |
| newOutcome[i] = array[i]; | |
| } | |
| results.add(newOutcome); | |
| } | |
| } | |
| } | |
| previousExpectedOutcome = previousExpectedOutcome * expectedOutcomeForEachResult; | |
| } | |
| return new ArrayList<>(results); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment