package com.jwetherell.algorithms.mathematics; import java.util.LinkedList; import java.util.List; /** * In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence * or order, or if the set is already ordered, rearranging (reordering) its elements, a process called permuting. *

* http://en.wikipedia.org/wiki/Permutation *
* @author Justin Wetherell * @author Lucjan Roslanowski */ public class Permutations { private Permutations() { } /** * N! permutation of the characters in the string (in order) */ public static String[] permutations(String stringToGeneratePermutationsFrom) { final int size = numberOfPermutations(stringToGeneratePermutationsFrom.length()); final String[] list = new String[size]; final char[] prefix = new char[0]; final char[] chars = stringToGeneratePermutationsFrom.toCharArray(); permutations(list, 0, prefix, chars, 0, chars.length); return list; } private static final int numberOfPermutations(int N) { // factorial int result = N; while (N > 1) result *= --N; return result; } private static final int permutations(String[] list, int index, char[] prefix, char[] remaining, int prefixLength, int remainingLength) { final int N = remainingLength-prefixLength; if (N == 0) { list[index]=new String(prefix); index++; } else { for (int i=0; i * int numbers[] = {7,5,3}; * LinkedList> result = getAllPermutations(numbers); */ public static final List> getAllPermutations(final N[] numbers){ final List> result = new LinkedList>(); return getAllPermutations(numbers, result); } private static final List> getAllPermutations(final N[] numbers, List> result){ //numbers given in an array are also a permutation LinkedList firstPermutation = new LinkedList(); for (N el : numbers) firstPermutation.add(el); result.add(firstPermutation); //let's permute all elements in array starting from index 0 return permute(numbers, 0, result); } private static final List> permute(final N[] numbers, int currentElementIndex, List> result){ if(currentElementIndex == numbers.length - 1) return result; for(int i = currentElementIndex; i < numbers.length; ++i){ //swapping two elements N temp = numbers[i]; numbers[i] = numbers[currentElementIndex]; numbers[currentElementIndex] = temp; permute(numbers, currentElementIndex + 1,result); //all next permutation found if(i != currentElementIndex){ LinkedList nextPermutation = new LinkedList(); for(int j = 0; j < numbers.length; j++) nextPermutation.add(numbers[j]); result.add(nextPermutation); } //swapping back two elements temp = numbers[i]; numbers[i] = numbers[currentElementIndex]; numbers[currentElementIndex] = temp; } return result; } }