Pages

List Permutations

import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

class Printer
{
    public static <E> void print(List<List<E>> permutations)
    {
        int n = 0;
        for (List<E> permutation : permutations)
        {
            System.out.print(++n + ":");
            for (E element : permutation)
            {
                System.out.print(" " + element);
            }
            System.out.println();
        }
    }
}

class Permuter
{
    public static <E> List<List<E>> getPermutationsOf(Set<E> set)
    {
        ArrayList list = new ArrayList(set.size());
        for (E element : set) list.add(element);
        return getPermutationsOf(list, 0);
    }
    public static <E> List<List<E>> getPermutationsOf(List<E> list)
    {
        return getPermutationsOf(list, 0);
    }
    private static <E> List<List<E>> getPermutationsOf(List<E> list, int headIndex)
    {
        final int permutationLength = list.size() - headIndex;
        List<List<E>> permutations = new ArrayList<List<E>>();
        if (permutationLength > 0)
        {
            E theHeadElement = list.get(headIndex);
            List<List<E>> permutationsOfTail = getPermutationsOf(list, headIndex + 1);
            for (List<E> permutationOfTail : permutationsOfTail)
            {
                final int lastIndex = permutationLength - 1;
                for (int putHeadAtIndex = 0; putHeadAtIndex <= lastIndex; putHeadAtIndex++)
                {
                    List<E> newPermutation = new ArrayList<E>(permutationLength);
                    for (int i = 0; i < lastIndex; i++)
                    {
                        E nextTailElement = permutationOfTail.get(i);
                        if (putHeadAtIndex == i)
                        {
                            newPermutation.add(theHeadElement);
                        }
                        newPermutation.add(nextTailElement);
                    }
                    if (putHeadAtIndex == lastIndex)
                    {
                        newPermutation.add(theHeadElement);
                    }
                    permutations.add(newPermutation);
                }
                
            }
        }
        else
        {
            // There is one way to arrange no elements.
            permutations.add(new ArrayList<E>());
        }
        return permutations;
    }
}

public class ListPermutations
{
    public static void main(String[] args)
    {
        SortedSet<String> set = new TreeSet<String>();
        for (String s : args) set.add(s);
        Printer.print(Permuter.getPermutationsOf(set));
    }
}