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.


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) {
List source = 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
List target = new LinkedList();

combine(source, target);

}

public static void combine(List source, 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
List reducedSource = (List)SerializationUtils.clone((LinkedList)source);
reducedSource.remove(position);
List combinedTarget = (List)SerializationUtils.clone((LinkedList)target);
combinedTarget.add(position);
combine(reducedSource, combinedTarget);
}
}
}

Followers