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

Popular posts from this blog

Java important topics list for interviews

Tough Sql practise questions for interviews involving SELECT queries - Part 2

DBMS important topics list for interviews

Program to find number lines and words in a given file

Tough Sql practise questions for interviews involving SELECT queries - Part 1

Producer Consumer Problem with Blocking Queue in Java.

Animation for String search - KMP Algorithm

Interactive Data Structure visualizations/animations for algorithms

Replace Occurances of the given string