The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer n
. These are the lists of numbers from 1
to n
whose sum is n
. For example, given input n = 4
, the result should be:
4
1, 3
3, 1
2, 2
2, 1, 1
1, 2, 1
1, 1, 2
1, 1, 1, 1
The result can be in any order, but must contain each ordered partition once. This means that for n = 4
, [1, 1, 2]
, [1, 2, 1]
and [2, 1, 1]
must all be part of the result.
Here's my own JavaScript code which achieves this:
function range(n) {
for (var range = [], i = 0; i < n; range.push(++i));
return range;
}
function composition(n) {
return n < 1 ? [[]] : range(n).map(function(i) {
return composition(n - i).map(function(j) {
return [i].concat(j);
});
}).reduce(function(a, b) {
return a.concat(b);
});
}
Golfed, ES6 (169 167 119 109 105 89 85 bytes):
n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]