import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
/**
*
* @author Andreou Dimitris, email: jim.andreou (at) gmail (dot) com
*/
public class Permutator {
private Permutator() { }
public static Iterable> permutations(final List list) {
return new Iterable>() {
public Iterator> iterator() {
return new Iterator>() {
private int current = 0;
private final long length = factorial(list.size());
public List next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
List permutation = new ArrayList(list);
int k = current;
for (int j = 2; j <= list.size(); j++) {
k /= j - 1;
Collections.swap(permutation, (k % j), j - 1);
}
current++;
return permutation;
}
public void remove() {
throw new UnsupportedOperationException();
}
public boolean hasNext() {
return current < length;
}
};
}
};
}
private static long factorial(int k) {
long factorial = 1L;
for (int i = 2; i <= k; i++) {
factorial *= i;
}
return factorial;
}
}
// * @author Andreou Dimitris, email: jim.andreou (at) gmail (dot) com
/*
class PermutatorTest extends TestCase {
public PermutatorTest(String testName) {
super(testName);
}
public void testPermutations() {
List list = Arrays.asList(1, 2, 3, 4, 5, 6);
Set> allLists = new HashSet>();
for (List permutation : Permutator.permutations(list)) {
allLists.add(permutation);
}
assertEquals(allLists.size(), 1 * 2 * 3 * 4 * 5 * 6);
}
}
*/