|
| 1 | +package com.jwetherell.algorithms.mathematics; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | + |
| 5 | + |
| 6 | +/* |
| 7 | + * Recursive permutations generating |
| 8 | + * @author Lucjan Roslanowski <lucjanroslanowski@gmail.com> |
| 9 | + * |
| 10 | + * Example of usage: |
| 11 | + * int numbers[] = {7,5,3}; |
| 12 | + * LinkedList<LinkedList<Integer>> result = new LinkedList<LinkedList<Integer>>(); |
| 13 | + * getAllPermutations(numbers,result); |
| 14 | + */ |
| 15 | + |
| 16 | +public class Permutations { |
| 17 | + |
| 18 | + public static LinkedList<LinkedList<Integer>> getAllPermutations(final int[] numbers, LinkedList<LinkedList<Integer>> result){ |
| 19 | + //numbers given in an array are also a permutation |
| 20 | + LinkedList<Integer> firstPermutation = new LinkedList<>(); |
| 21 | + for(int el : numbers){ |
| 22 | + firstPermutation.add(new Integer(el)); |
| 23 | + } |
| 24 | + result.add(firstPermutation); |
| 25 | + //let's permute all elements in array starting from index 0 |
| 26 | + return permute(numbers, 0, result); |
| 27 | + } |
| 28 | + |
| 29 | + public static LinkedList<LinkedList<Integer>> permute(final int[] numbers, |
| 30 | + int currentElementIndex, LinkedList<LinkedList<Integer>> result){ |
| 31 | + if(currentElementIndex == numbers.length - 1){ |
| 32 | + return result; |
| 33 | + } |
| 34 | + |
| 35 | + for(int i = currentElementIndex; i < numbers.length; ++i){ |
| 36 | + //swapping two elements |
| 37 | + int temp = numbers[i]; |
| 38 | + numbers[i] = numbers[currentElementIndex]; |
| 39 | + numbers[currentElementIndex] = temp; |
| 40 | + |
| 41 | + permute(numbers, currentElementIndex + 1,result); |
| 42 | + |
| 43 | + //all next permutation found |
| 44 | + if(i != currentElementIndex){ |
| 45 | + LinkedList<Integer> nextPermutation = new LinkedList<>(); |
| 46 | + for(int j = 0; j < numbers.length; j++) |
| 47 | + nextPermutation.add(new Integer(numbers[j])); |
| 48 | + result.add(nextPermutation); |
| 49 | + } |
| 50 | + |
| 51 | + //swapping back two elements |
| 52 | + temp = numbers[i]; |
| 53 | + numbers[i] = numbers[currentElementIndex]; |
| 54 | + numbers[currentElementIndex] = temp; |
| 55 | + } |
| 56 | + return result; |
| 57 | + } |
| 58 | + |
| 59 | + |
| 60 | +} |
0 commit comments