Permutations Code
import java.util.ArrayList;
import java.util.List;
/**
* // Pseudocode
* // Rule1: Return that permutation alone.
* // Rule2: ab >1 try to pick the last element seperately
* // and rest of the elements seperately lastelement, rest
* // Recursively // Position last element at all the possible
* places. // merge the last element
*
*/
public class Permutations {
static List<String> merge(List<String> list, String ch) {
List<String> mergedResult = new ArrayList<String>();
for (String element : list) {
// ab ch = 'c'
for (int i = 0; i <= element.length(); i++) { // ab c
String ps = new StringBuffer(element).insert(i, ch).toString();
mergedResult.add(ps);
}
}
return mergedResult;
}
// a
static List<String> permutation(String input) {
List<String> result = new ArrayList<String>();
// Rule1
if (input.length() == 1) {
result.add(input);
} else if (input.length() > 1) {
// Rule 2
int lastIndex = input.length() - 1;
// ab c
String last = input.substring(lastIndex);// c
String rest = input.substring(0, lastIndex);// ab
result = merge(permutation(rest), last);
}
return result;
}
public static void main(String[] args) {
System.out.println(permutation("abc"));
}
}
Comments
Post a Comment