import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang.SerializationUtils;
public class Combinations {
private final static String characters = "abcd";
private static int length = characters.length();
public static void main(String[] args) {
Listsource = new LinkedList ();
// form the source list that have all the possible positions
for (int i = 0; i < length; i++) {
source.add(i);
}
// create a target list for forming unique combinations
Listtarget = new LinkedList ();
combine(source, target);
}
public static void combine(Listsource, List target) {
// break the recursion
if (target.size() == length) {
for (int i = 0; i < length; i++) {
System.out.print(characters.charAt(target.get(i)));
}
System.out.println();
return;
}
for (Integer position : source) {
//form the target combination by selecting a position from the source
ListreducedSource = (List )SerializationUtils.clone((LinkedList )source);
reducedSource.remove(position);
ListcombinedTarget = (List )SerializationUtils.clone((LinkedList )target);
combinedTarget.add(position);
combine(reducedSource, combinedTarget);
}
}
}
Monday, March 26, 2012
Java program that does Permutation & Combination
Forms the unique target combinations, recursively, starting from source list that has all the positions.
Subscribe to:
Posts (Atom)