I have an integer and a list of non-negative weights, how can I 'split' the integer into same number of 'buckets' with corresponding weights?
public int[] SplitIntoBuckets(int count, int[] weights) {
// some magic algorithm
Debug.Assert(solution.Sum() == count);
return solution;
}
A trivial example would be count = 200
and weights = { 25, 25, 50 }
with solution {50, 50, 100}
(50+50+100 = 200). The inputs, however, does not have to be 'nice' numbers, another example without nice solution would be count = 150
and weights {753, 42, 95, 501}
.
The sum of buckets must be always equal to the count
input, the algorithm should distribute the input among buckets as closely to weights as possible. What is as 'close as possible' does not matter (for example it could be either lowest absolute, relative or squared error).
The closest questions I could find are Split evenly into buckets, however my buckets are not 'even' and Split randomly into buckets however the weights are chosen randomly to be 'nice' numbers.