Natantantan
Natantantan

Reputation: 47

How to put all possible permutations of a string into an array?

So I'm using the classic algorithm for permutations which is

private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) System.out.println(prefix);
    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
} 

The only thing I can't figure out how to do is how to store the permutations into an array instead of just printing them out. Any help is appreciated.

Upvotes: 0

Views: 1523

Answers (2)

JohnDoe90
JohnDoe90

Reputation: 368

You could also just pass a reference of the list of permutations to the permutation method itself. This has the advantage of only creating one list.

private static List<String> permutation(String str) {
  List<String> perms = new ArrayList<>();
  permutation("", str, perms);

  return perms;
}

private static void permutation(String prefix, String str, List<String> perms) {
  int n = str.length();
  if ( n == 0 ) {
    perms.add(prefix);
  } else {
    for ( int i = 0; i < n; i++ )
      permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1,n), perms);
  }
}

List<String> perms = permutation("abcd");

Upvotes: 0

user3769706
user3769706

Reputation:

Try this method. This will return list of permutations

private static List<String> permutation(String prefix, String str) {
    List<String> permutations = new ArrayList<>();
    int n = str.length();
    if (n == 0) {
        permutations.add(prefix);
    }
    else {
        for (int i = 0; i < n; i++)
            permutations.addAll(permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)));
    }
    return permutations;
}

Using Arrays. JAVA 8 needed

private static String[] permutation(String prefix, String str) {
    String[] permutation = new String[]{};
    int n = str.length();
    if (n == 0) {
        permutation = new String[]{prefix};
    }
    else {
        for (int i = 0; i < n; i++)
            permutation = Stream.concat(Arrays.stream(permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n))),
                    Arrays.stream(permutation)).toArray(String[]::new);

    }
    return permutation;
}

Upvotes: 1

Related Questions