Platinum Partner

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();
	}
}
{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}