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.

Wednesday, June 16, 2010

My New BSG Macbook Decal

We just got new laptops at work and after being inspired by a few colleagues, I decided to decorate it with this very cool vinyl decal:


My son Jonah was really into it:


It was slightly challenging to apply (the vinyl kept sticking to the backer when I tried to separate it), but after a few minutes it was on and looks great. If you are interested in one for yourself, check out Crafty Gal Decals (So say we all!).