0

I have the following code that will generate the permutations of an entered string, but is it possible for it to be changed so that there is no use of the for loop, just recursion?

public static void findPermutations (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();
        }
      }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
chocotella
  • 89
  • 1
  • 9
  • Loops can always be written using recursion, and vice-versa. The big question is usually "performance vs readability". – Maroun Mar 21 '16 at 14:33
  • My feeling is that a solution without a loop would be quite unreadable. – Ole V.V. Mar 21 '16 at 14:34
  • `StringIndexOutOfBoundsException` isn't really something that should be caught as it it is completely avoidable by checking lengths and indices. – Paul Boddington Mar 21 '16 at 14:37

1 Answers1

0

Here is an answer that i found somewhere else so no credit to me. Can't find question again though

public class Permutations {

    // print N! permutation of the characters of the string s (in order)
    public  static void perm1(String s) { perm1("", s); }
    private static void perm1(String prefix, String s) 
    {
        int N = s.length();
        if (N == 0)
        {
            System.out.println(prefix);
        }
        else {
            for (int i = 0; i < N; i++)
               perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
        }

    }

    // print N! permutation of the elements of array a (not in order)
    public static void perm2(String s) {
        int N = s.length();
        char[] a = new char[N];
        for (int i = 0; i < N; i++)
            a[i] = s.charAt(i);
        perm2(a, N);
    }

    private static void perm2(char[] a, int n) {
        if (n == 1) {
            if(new String(a).contains("ncl-"))
                System.out.println(a);
            return;
        }
        for (int i = 0; i < n; i++) {
            swap(a, i, n-1);
            perm2(a, n-1);
            swap(a, i, n-1);
        }
    }  

    // swap the characters at indices i and j
    private static void swap(char[] a, int i, int j) {
        char c = a[i];
        a[i] = a[j];
        a[j] = c;
    }



    public static void main(String[] args) throws IOException {
        //String word = "nst n-eitoira cp2vmamoocnla1e k nfto-k7re id6";
        String word = "doggy";
        perm1(word);
        System.out.println();
        perm2(word);
    }
}
3kings
  • 838
  • 2
  • 13
  • 28