DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

shivaji has posted 4 posts at DZone. View Full User Profile

Java Program For Doing Permutation & Combination

03.27.2012
| 11237 views |
  • submit to reddit
        Forms the unique target combinations, recursively, starting from source list that has all the possible positions (chars).


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

		combine(source, target);

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