Over a million developers have joined DZone.

Java Program For Doing Permutation & Combination

·
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 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);			
		}
		source.clear();
		target.clear();
	}
}
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}