Proteome Informatics Group > Java Proteomic Library
 

Recipe 0.5. Generating combinations.

Problem

You want to generate all possible combinations C(p, n).

Solution

CombinationFactory may generate all combinations of p elements among n:

import import org.apache.commons.collections15.Transformer;

// build the factory
CombinationFactory factory = 
	CombinationFactory.newInstance();

// generate all the combinations
List<int[]> combs = factory.transform(3, 4);

// Display all combinations
System.out.println(CombinationFactory.toString(combs));
		
// Output
//----------------------------------------------------------
// [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]

Sometimes you just want to compute the number of combinations:

// just compute the number of possible combinations
int number = CombinationFactory.computeCombNumber(6, 20)

Assert.assertEquals(38760, number);

Discussion

See Also