Print string permutations with Java.

I wrote this just to exercise my old java skills. If you find a use for it, let me know what you did with it!

import java.util.*;
 
public class Permute {
   LinkedList<String> orig;
 
   public Permute(LinkedList<String> _orig) {
      orig = _orig;
   }
 
   public LinkedList<String> BuildPerms(LinkedList<String> thisOrig) {
      Iterator<String> itr = thisOrig.iterator();
      LinkedList<String> thisSol = new LinkedList<String>();
 
      while (itr.hasNext()) {
         LinkedList<String> copy = (LinkedList<String>) thisOrig.clone();
         String removed = itr.next();
         copy.remove(removed);
 
         if (copy.size() > 2) {
            LinkedList<String> computedPerms = BuildPerms(copy);
            for (String item : computedPerms) {
               // the first letter + this computed permutation
               thisSol.add(removed + item);
            }
         } else {
            thisSol.add(removed + copy.getFirst() + copy.getLast());
            thisSol.add(removed + copy.getLast() + copy.getFirst());
         }
      }
      return thisSol;
   }
}

I also have a driver you can use to play with it.

import java.util.*;
 
public class StringPermutations {
   public static void main(String[] args) {
      LinkedList<String> orig = new LinkedList<String>();
      orig.add("A");
      orig.add("B");
      orig.add("C");
      orig.add("D");
      //orig.add("E");
      //orig.add("F");
      //orig.add("G");
      //orig.add("H");
      //orig.add("I");
 
      Permute obj = new Permute(orig);
      LinkedList<String> solutions = obj.BuildPerms(obj.orig);
 
      for (String item : solutions) {
         System.out.println(item);
      }
   }
}
This entry was posted in Programming and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.