I needed some snippet to get the collection of all permutations of any collection of objects and there were no ready to use snippets within 5 minutes of searching google, so I wrote this myself and here it is in case you need it.
Code:
import java.util.ArrayList;
import java.util.Arrays;
/**
* Generates all permutations of a certain array of values.
* @author Maxime Meire
*
* @param <T> The type of the elements to be permuted.
*/
public class Permutations<T> {
private ArrayList<ArrayList<T>> permutations;
public Permutations(T[] values) {
permute(values);
}
private ArrayList<ArrayList<T>> permute(ArrayList<ArrayList<T>> permutations, ArrayList<T> permutation, ArrayList<T> values) {
if (values.isEmpty()) {
permutations.add(permutation);
return permutations;
}
for (int i = 0; i < values.size(); i++) {
ArrayList<T> newValues = new ArrayList<T>();
newValues.addAll(values);
T value = newValues.remove(i);
ArrayList<T> newPermutation = new ArrayList<T>();
newPermutation.addAll(permutation);
newPermutation.add(value);
permute(permutations, newPermutation, newValues);
}
return permutations;
}
private ArrayList<ArrayList<T>> permute(T[] values) {
ArrayList<ArrayList<T>> permutations = new ArrayList<ArrayList<T>>();
permute(permutations, new ArrayList<T>(), new ArrayList<T>(Arrays.asList(values)));
return this.permutations = permutations;
}
public ArrayList<ArrayList<T>> getPermutations() {
return permutations;
}
public void printPermutations() {
System.out.println("PRINTING " + permutations.size() + " PERMUTATIONS:");
for (ArrayList<T> p : permutations) {
String s = "";
T value;
for (int i = 0; i < p.size(); i++) {
value = p.get(i);
s += value.toString() + (i == p.size() - 1 ? "" : ",");
}
System.out.println(s);
}
}
}