Popular Posts

Tuesday, February 1, 2011

Permutations of a given string

In outline form,algorithm looks like :

If you're past the last position
Print the string
Return
Otherwise
For each letter in the input string
If it's marked as used, skip to the next letter
Else place the letter in the current position
Mark the letter as used
Permute remaining letters starting at current position + 1
Mark the letter as unused

Recursive Implementation :
Java code:
public class Permutations {

public static void main(String[] args) {
permutation("", "abc");
}

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));
}
}
}


Method 2:
import java.util.ArrayList;
import java.util.List;

public class Permutations {

public static void main(String[] args) {
List<String> permutations = getPermutations("abcd");
System.out.println(" size " + permutations.size());
for (int i = 0; i < permutations.size(); i++) {
System.out.println(permutations.get(i));
}
}

public static List<String> getPermutations(String word) {
if (word == null || word.length() == 0)
throw new NullPointerException();
ArrayList<String> result = new ArrayList<String>();
if (word.length() == 1) {
result.add(word);
return result;
}
List<String> temp = getPermutations(word
.substring(0, word.length() - 1));
for (String s : temp) {
List<String> joined = joinCharToString(s, word
.charAt(word.length() - 1));
result.addAll(joined);
}
return result;
}

public static List<String> joinCharToString(String ori, char aChar) {
if (ori == null || ori.length() == 0)
throw new NullPointerException();
List<String> result = new ArrayList<String>();
StringBuilder sb;
for (int i = 0; i < ori.length() + 1; i++) {
sb = new StringBuilder(ori);
sb.insert(i, aChar);
result.add(sb.toString());
}
return result;
}
}

Print all permutations with repetition of characters : 
Given a string of length n, print all permutation of the given string. Repetition of characters is allowed. Print these permutations in lexicographically sorted order
Examples:
Input: AB
Ouput: All permutations of AB with repetition are:
      AA
      AB
      BA
      BB
Java Code : 
public class Permutations {
public static void main(String[] args) {
String str = "abc";
char[] chars = str.toCharArray();
getPermutations(chars, "", str.length());
}

private static void getPermutations(char[] chars, String target, int length) {
if (length == 0) {
System.out.println(target);
return;
}

for (int i = 0; i < chars.length; i++) {
getPermutations(chars, target + chars[i], length - 1);
}
}
}

1 comment: