Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Program For Doing Permutation & Combination

DZone's Guide to

Java Program For Doing Permutation & Combination

·
Free Resource
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:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}