0

My code seems to get me the correct results so far. Except I've run into a problem. When I give it a string that is 8 characters long or longer, it doesn't seem to end. I'm already at 3 billion permutations and it's still running. When I tried the method with shorter strings, it terminated and gave correct output. I don't know what else to try and I'd appreciate any tips. Here is the Java code:

public static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) {
        permutations++;
        System.out.println(prefix);
        System.out.println("Permutations: " + permutations);
    } else {
        for (int i = 0; i < n; i++) {
            permutation(prefix + str.charAt(i),
                    str.substring(0, i) + str.substring(i + 1));
        }
    }
}
HandleThatError
  • 598
  • 7
  • 29

1 Answers1

1

This code works on Windows 8 and java 1.8. The example string is 9 characters long and yields the expected results. I'm not sure how you've declared "permutations", but I just used an int, which should work for you unless you are using strings longer than 12 characters. I haven't changed any of your code, by the way. It sounds like you are doing other stuff, not just printing out these permutations, so maybe your issue is with another piece of your code?

public class example{
   public static int permutations = 0;
   public static void main(String[] args){
      String myS = "abcdefghi";
      perms(myS);
      System.out.println(myS.length());
   }
   public static void perms(String s){
      permutation("",s);
   }
   public static void permutation(String prefix, String str){
      int n = str.length();
      if (n == 0){
         permutations++;
         System.out.println(prefix);
         System.out.println("Permutations: " + permutations);
      } else {
         for (int i = 0; i < n; i++){
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1));
         } 
      }
   }
}
Ryan
  • 11
  • 1