Wednesday, July 28, 2010

combinatoricslib: compositions

A composition of an integer n is a way of writing n as the sum of a sequence of (strictly) positive integers. Two sequences that differ in the order of their terms define different compositions of their sum, while they are considered to define the same partition of that number.
The sixteen compositions of 5 are:
1.5
2.4+1
3.3+2
4.3+1+1
5.2+3
6.2+2+1
7.2+1+2
8.2+1+1+1
9.1+4
10.1+3+1
11.1+2+2
12.1+2+1+1
13.1+1+3
14.1+1+2+1
15.1+1+1+2
16.1+1+1+1+1.


Example. Generate compositions of 5.

// create composition generator of 5
Generator<integer> compositionGenerator = new CompositionGenerator(5);

// create iterator
Iterator<combinatoricsvector<Integer>> compositionIterator = compositionGenerator.createIterator();

// go through the iterator
while (compositionIterator.hasNext()) {
CombinatoricsVector<integer> composition = compositionIterator.next();
System.out.println(partitionIterator);
}

And the result

CompositionIterator=[#1, CombinatoricsVector=[[5]], size=1]]
CompositionIterator=[#2, CombinatoricsVector=[[1, 4]], size=2]]
CompositionIterator=[#3, CombinatoricsVector=[[2, 3]], size=2]]
CompositionIterator=[#4, CombinatoricsVector=[[1, 1, 3]], size=3]]
CompositionIterator=[#5, CombinatoricsVector=[[3, 2]], size=2]]
CompositionIterator=[#6, CombinatoricsVector=[[1, 2, 2]], size=3]]
CompositionIterator=[#7, CombinatoricsVector=[[2, 1, 2]], size=3]]
CompositionIterator=[#8, CombinatoricsVector=[[1, 1, 1, 2]], size=4]]
CompositionIterator=[#9, CombinatoricsVector=[[4, 1]], size=2]]
CompositionIterator=[#10, CombinatoricsVector=[[1, 3, 1]], size=3]]
CompositionIterator=[#11, CombinatoricsVector=[[2, 2, 1]], size=3]]
CompositionIterator=[#12, CombinatoricsVector=[[1, 1, 2, 1]], size=4]]
CompositionIterator=[#13, CombinatoricsVector=[[3, 1, 1]], size=3]]
CompositionIterator=[#14, CombinatoricsVector=[[1, 2, 1, 1]], size=4]]
CompositionIterator=[#15, CombinatoricsVector=[[2, 1, 1, 1]], size=4]]
CompositionIterator=[#16, CombinatoricsVector=[[1, 1, 1, 1, 1]], size=5]]

Please, read more here.