Monday, June 28, 2010

Recursively Find Permutations of a List in Java

I recently needed to implement an algorithm to find all orderings of a list in Java. Using google I found some code for finding all permutations of a string:

public class MainClass {
  public static void main(String args[]) {
    permuteString("", "String");
  }

  public static void permuteString(String beginningString, String endingString) {
    if (endingString.length() <= 1)
      System.out.println(beginningString + endingString);
    else
      for (int i = 0; i < endingString.length(); i++) {
        try {
          String newString = endingString.substring(0, i) + endingString.substring(i + 1);

          permuteString(beginningString + endingString.charAt(i), newString);
        } catch (StringIndexOutOfBoundsException exception) {
          exception.printStackTrace();
        }
      }
  }
}

My quick and dirty conversion to do the same with a List follows:

  public static void permutateList( List<String> startList, List<String> endList, List<List<String>> result )
  {
    if (endList.size() <= 1)
    {
      List<String> permResult = new ArrayList<String>();
      permResult.addAll(startList);
      permResult.addAll(endList);
      result.add(permResult);
    }
    else
    {
      for (int i = 0; i < endList.size(); i++)
      {
        List<String> newEndList = new ArrayList<String>();
        for ( int j = 0; j < i; j++ ) newEndList.add(endList.get(j));
        for ( int j = i+1; j < endList.size(); j++ ) newEndList.add(endList.get(j));

        List<String> newStartList = new ArrayList<String>();
        newStartList.addAll(startList);
        newStartList.add(endList.get(i));

        permutateList(newStartList, newEndList, result);
      }
    }
  }

Call it with an empty list for the first parameter, a source list that you want to find permutations for in the second parameter, and an empty List of Lists to contain the results. I am sure there are ways to make this more efficient (please comment), but it works.

No comments:

Post a Comment