Skip to main content

version 10 - Partitioning a list in n sublists with constrains in their sums


Is there a way to put cluster level limits on clusters? For example, if I run:


FindClusters[{1, 2, 3, 4, 4, 6, 7, 10}]

I get back two lists, {{1, 2, 3, 4, 4}, {6, 7, 10}}. But lets say I only want each cluster to have a sum of 15 or fewer and potentially get {{2, 3, 10}, {6, 3, 1}, {7, 4, 4}}



As far as I can tell, this is not possible to express with a distance function, so maybe clustering is the wrong tool for the job?


Is there a way to do that?



Answer



Quiet[<< Combinatorica`;]
l = {1, 2, 3, 4, 4, 6, 7, 10};
f[l_, n_, min_, max_] := Module[{part, s},
While[(s = (Tr /@ (part = RandomKSetPartition[l, n]));
Not[And @@ Thread[min < s < max]])];
part]
f[l, 3, 5, 15]

(* {{1, 10}, {2, 4, 7}, {3, 4, 6}} *)

Comments