23
2
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]))):[[]]
3
Welcome to the site! You need to specify a winning criterion. Code-golf maybe? Also, does it have to be in that specific order? If so, how is the order defined in general? I think lexicographical order would be more meaningful; or better yet, allow any order. You may want to use the sandbox for future challenges before posting them here
– Luis Mendo – 2016-09-22T09:08:51.123This is not strictly a duplicate since this one requires to output all lists, even those that are the same up to the ordering, whereas the previous one requires that only one of those is printed. – Fatalize – 2016-09-22T09:14:07.727
3@Fatalize Here [2 1 1] is different from [1 2 1], unlike there. I suspect the approaches may be significantly different – Luis Mendo – 2016-09-22T09:14:10.343
3To those who closed as dupe: are you sure the difference indicated in comments is not relevant? I'm not voting to reopen, as I think the hammer would work in that direction too – Luis Mendo – 2016-09-22T09:30:20.820
3I'd suggest not accepting an answer yet (even though you can change it at any time) because seeing the question accepted on the front page might make people think it's over and not participate. – xnor – 2016-09-22T09:50:35.613
5
The usual term for these ordered partitions is "compositions".
– Greg Martin – 2016-09-22T17:54:27.8732Some languages might be well-suited to the following "stars and bars" algorithm: starting with a string of n
1
s, there are n-1 possible places to insert a separator character such as_
, and thus 2^(n-1) possible choices of separator insertions. These correspond to the 2^(n-1) compositions of n. For example, the eight compositions of 4 in the OP correspond to the eight strings1111
,1_111
,111_1
,11_11
,11_1_1
,1_11_1
,1_1_11
, and1_1_1_1
. – Greg Martin – 2016-09-22T18:31:27.633