I am scratching my head trying to do this and it\'s eating me up. I know it is not THAT complex. I have a number of items, this number can be equal or greater than three. Then I
Here's an algorithm (expressed in C++) to solve a more general version of the problem, with arbitrary upper and lower bounds on the addends that may appear in each partition:
#include
#include
using namespace std;
typedef vector Partition;
typedef vector Partition_list;
// Count and return all partitions of an integer N using only
// addends between min and max inclusive.
int p(int min, int max, int n, Partition_list &v)
{
if (min > max) return 0;
if (min > n) return 0;
if (min == n) {
Partition vtemp(1,min);
v.push_back(vtemp);
return 1;
}
else {
Partition_list part1,part2;
int p1 = p(min+1,max,n,part1);
int p2 = p(min,max,n-min,part2);
v.insert(v.end(),part1.begin(),part1.end());
for(int i=0; i < p2; i++)
{
part2[i].push_back(min);
}
v.insert(v.end(),part2.begin(),part2.end());
return p1+p2;
}
}
void print_partition(Partition &p)
{
for(int i=0; i < p.size(); i++) {
cout << p[i] << ' ';
}
cout << "\n";
}
void print_partition_list(Partition_list &pl)
{
for(int i = 0; i < pl.size(); i++) {
print_partition(pl[i]);
}
}
int main(int argc, char **argv)
{
Partition_list v_master;
int n = atoi(argv[1]);
int min = atoi(argv[2]);
int max = atoi(argv[3]);
int count = p(min,max,n,v_master);
cout << count << " partitions of " << n << " with min " << min ;
cout << " and max " << max << ":\n" ;
print_partition_list(v_master);
}
And some sample output:
$ ./partitions 12 3 7
6 partitions of 12 with min 3 and max 7:
6 6
7 5
4 4 4
5 4 3
6 3 3
3 3 3 3
$ ./partitions 50 10 20
38 partitions of 50 with min 10 and max 20:
17 17 16
18 16 16
18 17 15
19 16 15
20 15 15
18 18 14
19 17 14
20 16 14
19 18 13
20 17 13
19 19 12
20 18 12
13 13 12 12
14 12 12 12
20 19 11
13 13 13 11
14 13 12 11
15 12 12 11
14 14 11 11
15 13 11 11
16 12 11 11
17 11 11 11
20 20 10
14 13 13 10
14 14 12 10
15 13 12 10
16 12 12 10
15 14 11 10
16 13 11 10
17 12 11 10
18 11 11 10
15 15 10 10
16 14 10 10
17 13 10 10
18 12 10 10
19 11 10 10
20 10 10 10
10 10 10 10 10